当前位置:   article > 正文

vue + UEditor 上传图片(回显),上传附件 含token_vue-neditor-wrap serverurl token

vue-neditor-wrap serverurl token

@[TOC](vue + UEditor 上传图片(回显),上传附件 含token)

背景介绍

本来一开始用的是TinyMCE的文本编辑器,但是谁还没遇到个无理的甲方爸爸呢,硬要换成已经不再维护好久的ueditor,后台不愿意改接口,只好硬着头皮上了

安装

参考vue-ueditor-wrap的官网安装就行
我用的vue2

npm i vue-ueditor-wrap@2.x
# 或者
yarn add vue-ueditor-wrap@2.x
  • 1
  • 2
  • 3

下载ueditor,我下载的是ueditor-dev-1.5.0,不多说
下载解压后放在static文件夹下
在这里插入图片描述
这是我的页面结构,把富文本编辑器单独变成一个组件,接口以项目实际为准

<template>
  <div>
    <vue-ueditor-wrap
      v-model="content"
      :config="editorConfig"
      editor-id="editor"
    ></vue-ueditor-wrap>
      
<!--@ready="ueditorReady"  -->
  </div>
</template>
<script>
import VueUeditorWrap from "vue-ueditor-wrap";
export default {
  data() {
    return {
      editorConfig: {
        // 编辑器不自动被内容撑高
        autoHeightEnabled: true,
        serverUrl: "http://xxx.com/api/uploads", // 服务端地址
        imageActionUrl:"http://xxx.com/api/uploads",//图片上传地址
        fileActionUrl:"http://xxx.com/api/uploads",
        imageAllowFiles:[".png",".jpg",".jpeg",",gif"],//图片上传类型限制
        imageMaxSize:2048000,//图片限制大小2M以内
        fileAllowFiles:[".pdf","doc","docx","zip","rar"],//文件上传类型限制
      },
      content: "", //网页内容
    };
  },
  components: {
    VueUeditorWrap,
  },
  watch: {
    content(val) {
      this.$emit("onEditorChange", val);
    },
  },
};
</script>
<style lang="less" scoped>
</style>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

配置ueditor根路径

不清楚的可以看ueditor官网配置在这里插入图片描述
接着把ueditor.all.js重命名为ueditor.all.min.js便于修改
这是我的接口结构,请求时需要头部加token,然后加上参数type区别文件类型,上传文件后,接口返回访问链接
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

修改图片并回显

首先修改ueditor.all.min.js
大概在8830行的位置

// core/loadconfig.js
  (function () {
    UE.Editor.prototype.loadServerConfig = function () {
      var me = this;
      setTimeout(function () {
        try {
          me.options.imageUrl &&
            me.setOpt(
              "serverUrl",
              me.options.imageUrl.replace(
                /^(.*[\/]).+([\.].+)$/,
                "$1controller$2"
              )
            );

          var configUrl = me.getActionUrl("serverUrl"),
          isJsonp = utils.isCrossDomainUrl(configUrl);
          console.log(isJsonp, 'isJsonp',configUrl)
          /* 发出ajax请求 */
          configUrl &&
            UE.ajax.request(configUrl, {
              method: 'POST',
              dataType: 'json',
              data: {},
              onsuccess: function (r) {
                try {
                  console.log(r, 'success')

                } catch (e) {
                  console.log('请求失败', e)
                  showErrorMsg(me.getLang("loadconfigFormatError"));
                }
              },
              onerror: function () {
                showErrorMsg(me.getLang("loadconfigHttpError"));
              }
            });
        }
        catch (e) {
          console.log(e)
          showErrorMsg(me.getLang("loadconfigError"));
        }
      });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

修改部分,serveUrl实际就是组件传进来的配置
在这里插入图片描述
getActionUrl函数,因为我不是php,没有那些什么actionName直接注释叼

      getActionUrl: function (action) {
        var actionName = this.getOpt(action) || action,
          imageUrl = this.getOpt("imageUrl"),
          serverUrl = this.getOpt("serverUrl");

        if (!serverUrl && imageUrl) {
          serverUrl = imageUrl.replace(/^(.*[\/]).+([\.].+)$/, "$1controller$2");
        }

        if (serverUrl) {
          // 修改的
          //   serverUrl =
          //     serverUrl +
          //     (serverUrl.indexOf("?") == -1 ? "?" : "&") +
          //     "type=" +
          //     (actionName || "");
          return utils.formatUrl(serverUrl);
        } else {
          return "";
        }
      }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

修改dialog/image/image.js,找到uploadBeforeSend的这个地方,直接删掉原来的,加上需要的参数和token

            uploader.on('uploadBeforeSend', function (file, data, header) {
                //这里可以通过data对象添加POST参数
                header['Authorization'] = sessionStorage.getItem('token') || '';
                data.type = 'text_pic'
            });
  • 1
  • 2
  • 3
  • 4
  • 5

这个是接口成功后,按照实际情况修改,我这里的src就直接是接口返回的data

        getInsertList: function () {
            var i, data, list = [],
                align = getAlign()
            // prefix = editor.getOpt('imageUrlPrefix');
            // 修改插入的img路径
            for (i = 0; i < this.imageList.length; i++) {

                data = this.imageList[i];
                list.push({
                    src: data,
                    // _src:  data,
                    alt: data.original,
                    floatStyle: align
                });
            }
            return list;
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

回显跟显示错误等信息部分,都是修改这一段,按照实际的图片路径修改

            // 当有文件添加进来时执行,负责view的创建
            function addFile(file) {
                
                var $li = $('<li id="' + file.id + '">' +
                    '<p class="title">' + file.name + '</p>' +
                    '<p class="imgWrap"></p>' +
                    '<p class="progress"><span></span></p>' +
                    '</li>'),

                    $btns = $('<div class="file-panel">' +
                        '<span class="cancel">' + lang.uploadDelete + '</span>' +
                        '<span class="rotateRight">' + lang.uploadTurnRight + '</span>' +
                        '<span class="rotateLeft">' + lang.uploadTurnLeft + '</span></div>').appendTo($li),
                    $prgress = $li.find('p.progress span'),
                    $wrap = $li.find('p.imgWrap'),
                    $info = $('<p class="error"></p>').hide().appendTo($li),

                    showError = function (code) {
                        switch (code) {
                            case 'exceed_size':
                                text = lang.errorExceedSize;
                                break;
                            case 'interrupt':
                                text = lang.errorInterrupt;
                                break;
                            case 'http':
                                text = lang.errorHttp;
                                break;
                            case 'not_allow_type':
                                text = lang.errorFileType;
                                break;
                            default:
                                text = lang.errorUploadRetry;
                                break;
                        }
                        $info.text(text).show();
                    };

                if (file.getStatus() === 'invalid') {
                    showError(file.statusText);
                } else {
                    $wrap.text(lang.uploadPreview);
                    if (browser.ie && browser.version <= 7) {
                        $wrap.text(lang.uploadNoPreview);
                    } else {
                        uploader.makeThumb(file, function (error, src) {
                            if (error || !src) {
                                $wrap.text(lang.uploadNoPreview);
                            } else {
                                var $img = $('<img src="' + src + '">');
                                $wrap.empty().append($img);
                                $img.on('error', function () {
                                    $wrap.text(lang.uploadNoPreview);
                                });
                            }
                        }, thumbnailWidth, thumbnailHeight);
                    }
                    percentages[file.id] = [file.size, 0];
                    file.rotation = 0;

                    /* 检查文件格式 */
                    if (!file.ext || acceptExtensions.indexOf(file.ext.toLowerCase()) == -1) {
                        showError('not_allow_type');
                        uploader.removeFile(file);
                    }
                }

                file.on('statuschange', function (cur, prev) {
                    if (prev === 'progress') {
                        $prgress.hide().width(0);
                    } else if (prev === 'queued') {
                        $li.off('mouseenter mouseleave');
                        $btns.remove();
                    }
                    // 成功
                    if (cur === 'error' || cur === 'invalid') {
                        showError(file.statusText);
                        percentages[file.id][1] = 1;
                    } else if (cur === 'interrupt') {
                        showError('interrupt');
                    } else if (cur === 'queued') {
                        percentages[file.id][1] = 0;
                    } else if (cur === 'progress') {
                        $info.hide();
                        $prgress.css('display', 'block');
                    } else if (cur === 'complete') {
                    }

                    $li.removeClass('state-' + prev).addClass('state-' + cur);
                });

                $li.on('mouseenter', function () {
                    $btns.stop().animate({ height: 30 });
                });
                $li.on('mouseleave', function () {
                    $btns.stop().animate({ height: 0 });
                });

                $btns.on('click', 'span', function () {
                    var index = $(this).index(),
                        deg;

                    switch (index) {
                        case 0:
                            uploader.removeFile(file);
                            return;
                        case 1:
                            file.rotation += 90;
                            break;
                        case 2:
                            file.rotation -= 90;
                            break;
                    }

                    if (supportTransition) {
                        deg = 'rotate(' + file.rotation + 'deg)';
                        $wrap.css({
                            '-webkit-transform': deg,
                            '-mos-transform': deg,
                            '-o-transform': deg,
                            'transform': deg
                        });
                    } else {
                        $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~((file.rotation / 90) % 4 + 4) % 4) + ')');
                    }

                });

                $li.insertBefore($filePickerBlock);
            }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130

在这里插入图片描述
回显部分其实就是接口调用成功后返回的url

            uploader.on('uploadSuccess', function (file, ret) {
                var $file = $('#' + file.id);
                try {
                    var responseText = (ret._raw || ret),
                        json = utils.str2json(responseText);
                    if (json.code == 0) {
                        _this.imageList.push(json.data.url);
                        $file.append('<span class="success"></span>');
                    } else {
                        $file.find('.error').text(json.message).show();
                    }
                } catch (e) {
                    $file.find('.error').text(json.message).show();
                }
            });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

最后效果

在这里插入图片描述

上传附件

因为我的附件要延用上传的文件名,这里做了点修改
修改/dialog/attachment/attachment.js
这一段是看判断条件显示上传后预览icon的,自行修改
在这里插入图片描述
增加token,参数

            uploader.on('uploadBeforeSend', function (file, data, header) {
                // 新改的
                header['Authorization'] = sessionStorage.getItem('token')||'';
                data.type='text_file'
            });
  • 1
  • 2
  • 3
  • 4
  • 5

这是上传成功后,接口返回的数据,按照实际的返回结果添加到文件列表里
在这里插入图片描述
代码

            uploader.on('uploadSuccess', function (file, ret) {
                var $file = $('#' + file.id);
                try {
                    var responseText = (ret._raw || ret),
                        json = utils.str2json(responseText);
                    if (json.code == 0) {
                        _this.fileList.push({url:json.data.url,name:file.name});
                        console.log(_this.fileList,'返回的数据')
                        
                        $file.append('<span class="success"></span>');
                    } else {
                        $file.find('.error').text(json.message).show();
                    }
                } catch (e) {
                    $file.find('.error').text(lang.errorServerUpload).show();
                }
            });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

效果:
在这里插入图片描述
在这里插入图片描述

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号