编辑器自带上传网络链接图片本地上传图片需要自己设置

效果:

vue3 图片上传 axios_vue

 注意事项:

1、自定义上传方法来上传图片,使用FromData对象来传参,但是碰到了后端无法获取file参数的问题,如果是axios请求后端接口需要修改请求头。。

2、直接上传配置好后端接口,可能会有跨域问题,配置请求头可解决

3、成功上传图片后编辑器提示插入图片失败,需要根据编辑器的规范返回后端数据

4、使用代码高亮插件,引用js的时候这样写(import  highlight from '../../assets/highlight/highlight.js')会报错,改成(import  * as highlight from '../../assets/highlight/highlight.js')就好了

........

一些关于本地上传图片的配置

// 上传图片到服务器,对应的是controller层的@RequestMapping("/upload")
this.editor.customConfig.uploadImgServer = "/api/file/upload”;//接口名称
//自定义name,接收的时候图片文件的那么用这个,对应的是参数中的MultipartFile upimg名称,这个名称即上传到浏览器的参数名称
this.editor.customConfig.uploadFileName = "file_key”;//这个需要和后台商量上传图片的名称
// 上传图片的结果反馈
this.editor.customConfig.uploadImgHooks = {
before: function(xhr, editor, files) {
// 图片上传之前触发
// xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,files 是选择的图片文件
// 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
// return {
// prevent: true,
// msg: '放弃上传'
// }
// console.log("before:",xhr)
},
success: function(xhr, editor, result) {
// 图片上传并返回结果,图片插入成功之后触发
// xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果
// console.log("success:",result)
},
fail: function(xhr, editor, result) {
// 图片上传并返回结果,但图片插入错误时触发
// xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果
},
error: function(xhr, editor) {
// 图片上传出错时触发
// xhr 是 XMLHttpRequst 对象,editor 是编辑器对象
},
// 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式,可使用该配置
// (但是,服务器端返回的必须是一个 JSON 格式字符串!!!否则会报错)
customInsert: function(insertImg, result, editor) {
// 图片上传并返回结果,自定义插入图片的事件(而不是编辑器自动插入图片!!!)
// insertImg 是插入图片的函数,参数editor 是编辑器对象,result 是服务器端返回的结果
// 举例:假如上传图片成功后,服务器端返回的是 {url:'....'} 这种格式,即可这样插入图片:
var url = result.result.remote_path;
insertImg(url);
// result 必须是一个 JSON 格式字符串!!!否则报错
}
};
// }

WangEditor本地上传图片完整代码

前端代码:

<template>
 <div class="mgb20" ref='editor' style="width:100%;"></div>
</template>
<script>
import WangEditor from "wangeditor";
import  * as highlight from '../../assets/highlight/highlight.js'
import {onBeforeUnmount, onMounted, reactive, ref,getCurrentInstance} from "vue";

export default {
  name: "addArticle",
  setup() {
    const editor = ref(null);
    const $systemUrl = getCurrentInstance()?.appContext.config.globalProperties.$systemUrl;
    const content = reactive({
      html: "",
      text: "",
    });
    let instance;
    onMounted(() => {
      instance = new WangEditor(editor.value);
      instance.config.zIndex = 1;
      // 代码高亮
      instance.highlight = highlight;
      // 开启本地上传图片(这是后端上传链接)
      instance.config.uploadImgServer = $systemUrl + "/uploadForEditor";
      //设置上传图片http请求参数名,
      instance.config.uploadFileName = 'file';
      //设置请求头  解决跨域问题
      instance.config.uploadImgHeaders = {
        'Access-Control-Allow-Origin': 'origin'
      }
      // 一次最多上传图片的数量
      //instance.config.uploadImgMaxLength = 1;
      // 限制上传图片格式
      instance.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
      // 开启本地上传视频(这是后端上传链接)
      instance.config.uploadVideoServer = uploadUrl.value;
      instance.create();
      instance.txt.html('<p>要初始化的内容</p>')
    });
    onBeforeUnmount(() => {
      instance.destroy();
      instance = null;
    });
    const syncHTML = () => {
      content.html = instance.txt.html();
      console.log(content.html);
    };
    return {
      editor,
      content,
      syncHTML,
    };
  },
};
</script>

后端代码:

controller

@RequestMapping("/uploadForEditor")
    public Map<String, Object> uploadForEditor(MultipartFile file){

        return fileUploadService.uploadForEditor(file);

    }

service

@Value("${uploadFilePath}")
    private String uploadFilePath;
    @Value("${filePath}")
    private String filePath;


public Map<String, Object> uploadForEditor(MultipartFile file){
        Map<String, Object> map = new HashMap<String, Object>();
        if(Tools.isEmpty(file)){
            map.put("msg", "上传失败");
            map.put("errno", 1); //错误代码,0表示没有错误
            return map;
        }
        String path = Tools.uploadFile(file,uploadFilePath);
        //在上传图片成功,但是却会触发fail并显示errno=undefined的话说明
        // 后台放回的字段中没有errno需要加上此字段,还有若data有问题则需
        // 要加上data,data应该是一个数组,存储着图片的值的路径
        String[] arr = {uploadFilePath + path};
        map.put("data", arr);
        map.put("msg", "上传成功");
        map.put("errno", 0);
        return map;
    }

配置路径

#自定义配置内容

#文件上传本地路径 linux:/home/xxx/upload/otherImg/ 本地D:/zjblogImg/upload/otherImg/
uploadFilePath=D:/zjblogImg/upload/otherImg/
#文件访问路径
filePath=https://zjlovelt.com/xxx/xxxxImg/

Tools工具类上传方法

/**
     * @Description:文件上传
     * @param file
     * @return
     */
    public static String uploadFile(MultipartFile file, String path) {
        // 判断文件是否为空
        if (!file.isEmpty()) {
            try {
                // 获取3位的随机数
                int num = (int)(100 + Math.random() * (999 - 1 + 1));
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmsss");// 设置日期格式
                SimpleDateFormat dfm = new SimpleDateFormat("yyyyMM");// 设置日期格式
                String dateTime = df.format(new Date());
                String yearmonth = dfm.format(new Date());
                path += yearmonth;
                // 取文件格式后缀名
                String type = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
                // 上传文件名
                String fileName = dateTime + num + type;// 取当前时间戳作为文件名
                // 上传文件路径(保存项目根路径)
                // String path = request.getSession().getServletContext().getRealPath("/upload/otherImg");
                // 判断路径是否存在,如果不存在就创建一个
                File filePath = new File(path, fileName);
                if (!filePath.getParentFile().exists()) {
                    filePath.getParentFile().mkdirs();
                }
                // 转存文件
                file.transferTo(new File(path + File.separator + fileName));

                String newFileName =  dateTime + num + "_ys" + type;  //压缩后路径

              // 开始读取文件并进行压缩
                  Thumbnails.of(path + File.separator + fileName)
                        .scale(0.9f) // 图片缩放90%, 不能和size()一起使用
                          // 添加 水印图 watermark(位置,水印图,透明度)
                        //.watermark(Positions.BOTTOM_RIGHT,ImageIO.read(new File(path + File.separator + newFileName)),0.5f)
                        .outputQuality(0.4f)// 图片质量压缩到50%
                        .outputFormat(type.substring(1))  //图片后缀 亲测保持一样否则可能会变大
                        .toFile(path + File.separator + newFileName);

                return yearmonth + "/" + newFileName;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return " ";
    }