关于Egg.js中如何接收wangEditor上传的图片

74 阅读1分钟

环境

本文使用的是vue3+egg.js

解决方法

前端:server发送的是post请求,需要写好后端接口,并且'/api'不能少,否则会请求出错,'/tp'为我后端接收图片的接口。如果为ts只需添加类型即可.且wangEditor已经封装好了new FormData,后端直接用fs模块接收就行

    const editorConfig = { MENU_CONF: {} };
    //上传图片
    editorConfig.MENU_CONF["uploadImage"] = {
      server: "/api/tp",
    };

后端:img.js为我处理图片的接口文件,public/tp为存放图片的文件

image.png

img.js:注意返回值必须为官方定义的返回值,如果需要自定义,也可以去看官方文档www.wangeditor.com/

"use strict";

const { Controller } = require("egg");
const fs = require('fs');

class ImgController extends Controller {
    //上传的图片
    async tp(){
       let file= this.ctx.request.files[0]
        console.log(file);
       //定义文件去处
       let to = __dirname+"/../public/tp/"+ file.filename
       console.log(to,file.filepath);   
       //拷贝文件(跨盘就用copyFile,不跨盘就用rename)
       fs.copyFile(file.filepath, to, ()=>{
           //删除文件
           console.log(1111111);
       fs.unlink(file.filepath,()=>{
        console.log(22222);
        
       })
       });
       
       this.ctx.body={
        "errno": 0, 
        "data": {
            "url": `http://localhost:7001/public/tp/${file.filename}`, 
        }
    }
       
    }

}

module.exports = ImgController;

router.js:别忘了注册路由

//上传图片
  router.post('/tp', controller.img.tp)

效果

image.png