likes
comments
collection
share

Vue2 使用wangEditor5 上传图片

作者站长头像
站长
· 阅读数 34

wangEditor v5

wangEditor v5 是国内一名优秀的开发者开发的富文本编辑器,是一款非常好用的编辑器官网:wangEditor v5

vue2-cli 使用wangEditor v5

vue-cli安装使用请跳官网:vue-cli

安装:

yarn add @wangeditor/editor
# 或者 npm install @wangeditor/editor --save

yarn add @wangeditor/editor-for-vue
# 或者 npm install @wangeditor/editor-for-vue --save

使用

模板
<template>
    <div style="border: 1px solid #ccc;">
        <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editor"
            :defaultConfig="toolbarConfig"
            :mode="mode"
        />
        <Editor
            style="height: 500px; overflow-y: hidden;"
            v-model="html"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="onCreated"
        />
    </div>
</template>
script
<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default {
    components: { Editor, Toolbar },
    data() {
        return {
            editor: null,
            html: '<p>hello</p>',
            toolbarConfig: { },
            editorConfig: { placeholder: '请输入内容...' },
            mode: 'default', // or 'simple'
        }
    },
    methods: {
        onCreated(editor) {
            this.editor = Object.seal(editor) // 一定要用 Object.seal() ,否则会报错
        },
    },
    mounted() {
        // 模拟 ajax 请求,异步渲染编辑器
        setTimeout(() => {
            this.html = '<p>模拟 Ajax 异步设置内容 HTML</p>'
        }, 1500)
    },
    beforeDestroy() {
        const editor = this.editor
        if (editor == null) return
        editor.destroy() // 组件销毁时,及时销毁编辑器
    }
}
</script>
css
<style src="@wangeditor/editor/dist/css/style.css"></style>

到这就可以正常使用了,接下来教大家怎么上传图片和视频

上传图片与视频

我们先看一下文档关于上传图片和视频的说明上传图片和视频配置必须在uploadImage里进行配置

editorConfig.MENU_CONF['uploadImage'] = {
    // 上传图片的配置
}

直接给大家看我怎么配置的,直接在data里的editorConfig.MENU_CONF进行配置

   editorConfig: {
        placeholder: '请输入内容...',
        // autoFocus: false,
        // 所有的菜单配置,都要在 MENU_CONF 属性下
        MENU_CONF: {
          // 图片上传
          uploadImage: {
            server: '/api/blade-resource/fileSystem/fileUpload',
            fieldName: 'file',
            // 单个文件的最大体积限制,默认为 2M
            maxFileSize: 10 * 1024 * 1024, // 10M
            // 最多可上传几个文件,默认为 100
            maxNumberOfFiles: 10,
            // 选择文件时的类型限制,默认为 ['image/*'] 。如不想限制,则设置为 []
            allowedFileTypes: ['image/*'],
            // 自定义上传参数,例如传递验证的 token 等。参数会被添加到 formData 中,一起上传到服务端。
            meta: {
              // token: 'xxx',
              // otherKey: 'yyy'
              // file:''
            },
            // 将 meta 拼接到 url 参数中,默认 false
            metaWithUrl: false,

            // 自定义增加 http  header
            headers: {
              // Accept: 'text/x-json',
              // otherKey: 'xxx'
            },

            // 跨域是否传递 cookie ,默认为 false
            withCredentials: true,

            // 超时时间,默认为 10 秒
            timeout: 10 * 1000, //10 秒

            // 上传前
            onBeforeUpload(files) {
              Message({
                message: '图片正在上传中,请耐心等待',
                duration: 0,
                customClass: 'uploadTip',
                iconClass: 'el-icon-loading',
                showClose: true
              });
              return files;
            },
            // 自定义插入图片
            customInsert(res, insertFn) {
              // 因为自定义插入导致onSuccess与onFailed回调函数不起作用,自己手动处理
              // 先关闭等待的Message
              Message.closeAll();
              if (res.code === 200) {
                Message.success({
                  message: `${res.data.originalName} 上传成功`
                });
              } else {
                Message.error({
                  message: `${res.data.originalName} 上传失败,请重新尝试`
                });
              }
              insertFn(res.data.link, res.data.name, res.data.link);
            },

            // 单个文件上传成功之后
            onSuccess(file, res) {
              console.log(`${file.name} 上传成功`, res);
            },

            // 单个文件上传失败
            onFailed(file, res) {
              console.log(`${file.name} 上传失败`, res);
            },

            // 上传进度的回调函数
            onProgress(progress) {
              console.log('progress', progress);
              // progress 是 0-100 的数字
            },

            // 上传错误,或者触发 timeout 超时
            onError(file, err, res) {
              console.log(`${file.name} 上传出错`, err, res);
            }
          },
          // 视频上传
          uploadVideo: {
            fieldName: 'file',
            server: '/api/blade-resource/fileSystem/fileUpload',

            // 单个文件的最大体积限制,默认为 10M
            maxFileSize: 50 * 1024 * 1024, // 50M

            // 最多可上传几个文件,默认为 5
            maxNumberOfFiles: 3,
            // 选择文件时的类型限制,默认为 ['video/*'] 。如不想限制,则设置为 []
            allowedFileTypes: ['video/*'],

            // 自定义上传参数,例如传递验证的 token 等。参数会被添加到 formData 中,一起上传到服务端。
            meta: {
              // token: 'xxx',
              // otherKey: 'yyy'
            },

            // 将 meta 拼接到 url 参数中,默认 false
            metaWithUrl: false,

            // 自定义增加 http  header
            headers: {
              // Accept: 'text/x-json',
              // otherKey: 'xxx'
            },

            // 跨域是否传递 cookie ,默认为 false
            withCredentials: true,

            // 超时时间,默认为 30 秒
            timeout: 1000 * 1000, // 1000 秒,
            // 上传之前触发
            onBeforeUpload(file) {
              Message({
                message: '视频正在上传中,请耐心等待',
                duration: 0,
                customClass: 'uploadTip',
                iconClass: 'el-icon-loading',
                showClose: true
              });
              return file;
            },
            // 自定义插入视频
            customInsert(res, insertFn) {
              // 因为自定义插入导致onSuccess与onFailed回调函数不起作用,自己手动处理
              // 先关闭等待的Message
              Message.closeAll();
              if (res.code === 200) {
                Message.success({
                  message: `${res.data.originalName} 上传成功`
                });
              } else {
                Message.error({
                  message: `${res.data.originalName} 上传失败,请重新尝试`
                });
              }
              insertFn(res.data.link, res.data.link);
            },
            // 上传进度的回调函数
            onProgress(progress) {
              console.log(progress);
              // onProgress(progress) {       // JS 语法
              // progress 是 0-100 的数字
            },

            // // 单个文件上传成功之后
            // onSuccess(file, res) {
            //   console.log(`${file.name} 上传成功`, res);
            //   this.successMsg(file);
            // },

            // // 单个文件上传失败
            // onFailed(file, res) {
            //   console.log(`${file.name} 上传失败`, res);
            //   this.errorMsg(file);
            // },

            // 上传错误,或者触发 timeout 超时
            onError(file, err, res) {
              console.log(`${file.name} 上传出错`, err, res);
              Notification.error({
                title: '错误',
                message: `${file.name} 上传失败,请重新尝试`
              });
            }
          }
        }
      },

如果后端返回来的格式与富文本的格式一致,请把上面的自定义插入删除,忽略下面Vue2 使用wangEditor5 上传图片

如果需要格式不对,那其中最关键的一步就是自定义插入,官网文档描述:Vue2 使用wangEditor5 上传图片也就是说如果后端返回来的格式与富文本要求的格式无法一致,可以使用自定义插入来插入图片和视频,由于这里有一个小问题,使用自定义插入会导致onSuccess与onFailed回调函数不起作用,我便自己在customInsert进行处理,这个问题我已经反馈给作者,相信很快解决,各位小伙伴使用自定义插入的时候可以先看看回调函数是否起作用,如果有,可以把上面customInsert里面关于回调的处理去掉

结果

上传本地图片Vue2 使用wangEditor5 上传图片复制网络照片直接粘贴编辑器里Vue2 使用wangEditor5 上传图片上传本地视频Vue2 使用wangEditor5 上传图片