wangEditor服务器上传图片(Vue使用)

这两天在用wangEditor的时候在上传图片的时候遇到一些问题
有些地方也没有直接贴出源码只是贴了一些伪代码,
这里我将我练手的项目demo贴出来,这里只是例举了我的方案,具体操作建议观看


基本配置

如下

 editor.customConfig.showLinkImg = false  //关闭网络路径图片方式
 editor.customConfig.uploadImgServer = 'http://localhost:3000/upload' // 上传图片的接口地址
 editor.customConfig.uploadFileName = 'file' // formdata中的name属性

请求头

还有一个是请求头,后台在上传文件的时候需要添加请求头验证,此处我这边需要添加一个Authorization
代码如下

editor.customConfig.uploadImgHeaders = {
      Authorization: localStorage.getItem('toutoken') // 设置请求头
    }

开启debug模式

开启debug模式可以帮我们定位bug

    editor.customConfig.debug = true // 开启debug模式

设置监听函数

 editor.customConfig.uploadImgHooks = {
      // 图片上传并返回结果,但图片插入错误时触发
      fail: function (xhr, editor, result) {
        console.log(result)
      },
      success: function (xhr, editor, result) {
        // 图片上传并返回结果,图片插入成功之后触发
        console.log(result, 'success')
      }
    }

完整代码

<template>
  <div>
    <div id="editor" ref="editor">
      <p>
        欢迎使用
        <b>wangEditor</b> 富文本编辑器
      </p>
    </div>
  </div>
</template>

<script>
import Wangeditor from 'wangeditor'
export default {
  mounted () {
    const editor = new Wangeditor(this.$refs.editor)
    editor.customConfig.showLinkImg = false
    editor.customConfig.uploadImgServer = 'http://localhost:3000/upload' // 上传图片的接口地址
    editor.customConfig.uploadFileName = 'file' // formdata中的name属性
    editor.customConfig.debug = true // 开启debug模式
    editor.customConfig.uploadImgHeaders = {
      Authorization: localStorage.getItem('toutoken') // 设置请求头
    }
    editor.customConfig.uploadImgHooks = {
      // 图片上传并返回结果,但图片插入错误时触发
      fail: function (xhr, editor, result) {
        console.log(result)
      },
      success: function (xhr, editor, result) {
        // 图片上传并返回结果,图片插入成功之后触发
        console.log(result, 'success')
      }
    }
    editor.create()
  }
}
</script>

<style lang="less" scoped>
#editor {
   80%;
  margin: 0 auto;
}
</style>

遇到errno=undefined错误

在上传图片成功,但是却会触发fail并显示errno=undefined的话说明后台放回的字段中没有errno需要和后台沟通并加上此字段,还有若data有问题则需要与后台沟通,data应该是一个数组,存储着图片的值的路径

原文地址:https://www.cnblogs.com/axu1997/p/12877898.html