wangeditor富文本编辑器+node后台实现图片上传

前端:

<div id="editorElem" ref='editorElem' style={{textAlign: 'left'}}/>
    //富文本编辑器
    initEditor() {
        let editor = new E('#editorElem');
        let uploadUrl = 'http://localhost:3009/uploadImg';


        editor.customConfig.onchange = (html) => {
            this.editorContent = html
        };


//配置menus可以选择显示哪些菜单栏
        editor.customConfig.menus = [
            'head', // 标题
            'bold', // 粗体
            'fontSize', // 字号
            // 'fontName', // 字体
            'italic', // 斜体
            'underline', // 下划线
            'strikeThrough', // 删除线
            'foreColor', // 文字颜色
            // 'backColor', // 背景颜色
            'link', // 插入链接
            'list', // 列表
            'justify', // 对齐方式
            'quote', // 引用
            // 'emoticon', // 表情
            'image', // 插入图片
            // 'table', // 表格
            // 'video', // 插入视频
            // 'code', // 插入代码
            'undo', // 撤销
            'redo' // 重复
        ];
        editor.customConfig.lang = {
            '设置标题': 'Title',
            '字号': 'Size',
            '文字颜色': 'Color',
            '设置列表': 'List',
            '有序列表': '',
            '无序列表': '',
            '对齐方式': 'Align',
            '靠左': '',
            '居中': '',
            '靠右': '',
            '正文': 'p',
            '链接文字': 'link text',
            '链接': 'link',
            '上传图片': 'Upload',
            '网络图片': 'Web',
            '图片link': 'image url',
            '插入视频': 'Video',
            '格式如': 'format',
            '上传': 'Upload',
            '创建': 'init'
        };

        editor.customConfig.showLinkImg = false;
        editor.customConfig = {
            debug: true,//开启debug调试
            uploadImgServer: uploadUrl,//配置上传图片的接口api
            uploadImgMaxSize: 5 * 1024 * 1024,//图片大小限制为 5M
            uploadImgMaxLength: 10,// 限制一次最多上传 10 张图片
            uploadFileName: 'myFileName',//配置文件参数名(这个参数必需配置,后台用这个值接收图片)
            showLinkImg:false  //隐藏网络图片tab
        };


//监听函数在上传图片的不同阶段做相应处理
        editor.customConfig.uploadImgHooks = {
            success: function (xhr, editor, result) {
                console.log('图片上传并返回结果,图片插入成功')
            },
            fail: function (xhr, editor, result) {
                console.log('图片上传并返回结果,但图片插入错误')
            },
            error: function (xhr, editor) {
                console.log('图片上传出错')
            },
            timeout: function (xhr, editor) {
                console.log('图片上传超时')
            },
            customInsert: function (insertImg, result, editor) {
                console.log(' 图片上传并返回结果');
                var url = result.url[0];
                insertImg(url)
            }
        };

        editor.create()

    }

后端:

1.设置跨域

app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://localhost:3000");//运行跨域   来之http://localhost:3000域名的
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header('Access-Control-Allow-Credentials',true);//运行表头带cookie参数
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");


    next();
});

2.写接口:

app.post('/uploadImg', function (req, res, next) {
    let form = new formidable.IncomingForm();
    let dir = "./public/image/";
    form.uploadDir =dir;
    form.parse(req, function(err, fields, files) {
        let oldPath = files.fileName.path; //fileName就是我们刚在前台模板里面配置的后台接受的名称;
        let extname = files.fileName.name; //获取图片名称
        //新的路径由组成:原父路径 + 拓展名
        let newPath = dir + extname;
        //改名     把之前存的图片换成真的图片的完整路径
        fs.rename(oldPath, newPath, function(err) {
            if(err) {
                res.send({isOk:false,err});
            }
            let resPath = newPath.replace("./public","http://localhost:3009"); //处理图片路径  让前端能访问
            res.send({isOk:true,url:[resPath]}) //返回图片路径
        });
    });
})

3.设置静态资源映射路径以便前端访问图片

app.use(express.static(path.join(__dirname, 'public')));

后端目录:

效果:

PS:这里请求会有两次是因为涉及到跨域 

       

第一个的是  OPTIONS 类型的     是服务器发给客户端的 这个里面会返回一个post  

第二个才是真正的请求处理       

猜你喜欢

转载自blog.csdn.net/wangshang1320/article/details/88845731