webpack,node.js,vue.js集成的Ueditor

image.png

1、下载ueditor前端包

下载库包,http://ueditor.baidu.com/website/download.html

将\ueditor1_4_3_3-utf8-jsp\utf8-jsp目录移植到项目public\ueditor下

image.png

2、改造public\ueditor\ueditor.all.js文件,使它支持common.js规范

require("./ueditor.config");
var zhCn = require("./lang/zh-cn/zh-cn");
(function(){
    // editor.js
    UEDITOR_CONFIG = window.UEDITOR_CONFIG || {};
    var baidu = window.baidu || {};
    window.baidu = baidu;
    module.exports =  window.UE = baidu.editor =  window.UE || {};
    UE.plugins = {};
    UE.commands = {};
    UE.instants = {};
    UE.I18N = {};
    UE.I18N['zh-cn'] = zhCn;

    ...

3、改造\ueditor\ueditor.config.js文件,P22

window.UEDITOR_HOME_URL = "/ueditor/";
var URL = window.UEDITOR_HOME_URL || getUEBasePath();

/**
 * 配置项主体。注意,此处所有涉及到路径的配置别遗漏URL变量。
 */
window.UEDITOR_CONFIG = {
    //为编辑器实例添加一个路径,这个不能被注释
    UEDITOR_HOME_URL: URL

    // 服务器统一请求接口路径
    , serverUrl: URL + "ue"
    
    ...

4、cms-form.vue页面中引用

<script id="editor" type="text/plain" style="width:1024px;height:500px;"></script>
<script>
    var $ = require("jquery");
    var UE = require("../../ueditor/ueditor.all");
    export default {
        data () {
            return {
                ue : {

                }
            }
        },

        mounted:function () {
            this.ue = UE.getEditor('editor');
        },
        beforeDestroy:function () {
            UE.delEditor("editor");
            $("#edui_fixedlayer").remove();
            $("#global-zeroclipboard-flash-bridge").remove();
            $("#editor").remove();
        },
        methods: {

        }
    }
</script>

5、转储存图片到图片服务器,参考如下node.js路由

/**
 * Created by lin on 2017/5/11.
 */
var formidable = require("formidable");
var qs = require('querystring');//解析参数的库
var express = require('express');
var path = require('path');
var fs = require('fs');
var http = require('http');
var async = require('async');
const url = require('url');
var conf = require('../config/conf');// 图片服务器地址配置
module.exports = function (routeReq, routeRes, next) {
   if (routeReq.query.action === 'config') {
      routeRes.setHeader('Content-Type', 'application/json');
      routeRes.redirect('/ueditor/nodejs/config.json');
      return;
   } else if (routeReq.query.action === 'catchimage') {
      function factory(remoteUrl) {
         return function (callbackfirst) {
            async.waterfall([
               function(callback) {
                  var oUrl = url.parse(remoteUrl);
                  var aPath = oUrl.pathname.split("/");
                  var filename = aPath[aPath.length - 1];
                  http.get({
                     host: oUrl.hostname,
                     path: oUrl.pathname,
                     port: oUrl.port || 80
                  }, function (res) {
                     let rawData = '';
                     res.setEncoding("binary");
                     res.on('data', (chunk) => {
                        rawData += chunk;
                     });
                     res.on('end', () => {
                        try {
                           var data = new Buffer(rawData, "binary").toString('base64');
                           callback(null,data, filename);
                        } catch (e) {
                           callback(e);
                           console.error(e.message);
                        }
                     });
                  });
               }
            ], function (err, data,fileName) {
               var base64Data = data;
               var postData = {
                  data: base64Data,
                  filename: fileName
               };
               var sPostData = qs.stringify(postData);
               var options = {
                  hostname: conf.fileServer,
                  port: conf.fileServerPort,
                  path: conf.fileServerPath,
                  method: "POST",
                  headers: {
                     'Content-Type': 'application/x-www-form-urlencoded',
                     'Content-Length': Buffer.byteLength(sPostData)
                  }
               };
               var req = http.request(options, (res) => {
                  res.setEncoding('utf8');
                  var aResData = [];
                  res.on('data', (chunk) => {
                     aResData.push(chunk);
                  });
                  res.on('end', () => {
                     var resData = aResData.join("");
                     var data = resData.toString();
                     var jDate = JSON.parse(data);
                     var sResule = {};
                     if (jDate.code == "success") {
                        sResule.url = "http://" + conf.fileServer + ":" + conf.fileServerPort + jDate.path;
                        sResule.title = fileName;
                        sResule.source = remoteUrl;
                        sResule.state = "SUCCESS";
                        sResule.size = base64Data.length;
                     } else {
                        sResule.state = "Fail";
                     }
                     callbackfirst(null,sResule);
                  });
               });
               req.on('error', (e) => {
                  callbackfirst(e);
                  console.log(`请求遇到问题: ${e.message}`);
               });
               // 写入数据到请求主体
               req.write(sPostData);
               req.end();
            });
         }
      }
      var source = routeReq.body['source[]'];
      var aRemoteUrls = [];
      if (typeof source === "string") {
         aRemoteUrls.push(source);
      } else {
         aRemoteUrls = source;
      }
      var factorys = aRemoteUrls.map(factory);
      async.parallel(
         factorys,
         function (err, results) {
            if(err){
               next(err);
               return;
            }
            var result = {
               list: results,
               state: "SUCCESS"
            }
            routeRes.writeHead(200, {'Content-Type': 'application/json;charset=utf-8'});
            routeRes.end(JSON.stringify(result));
         }
      );
      
   } else {
      function sentPicToServer(data, fileName) {
         var base64Data = data;
         var postData = {
            data: base64Data,
            filename: fileName
         };
         var sPostData = qs.stringify(postData);
         var options = {
            hostname: conf.fileServer,
            port: conf.fileServerPort,
            path: conf.fileServerPath,
            method: "POST",
            headers: {
               'Content-Type': 'application/x-www-form-urlencoded',
               'Content-Length': Buffer.byteLength(sPostData)
            }
         };
         var req = http.request(options, (res) => {
            res.setEncoding('utf8');
            var aResData = [];
            res.on('data', (chunk) => {
               aResData.push(chunk);
            });
            res.on('end', () => {
               var resData = aResData.join("");
               routeRes.writeHead(200, {'Content-Type': 'application/json;charset=utf-8'});
               var data = resData.toString();
               var jDate = JSON.parse(data);
               var sResule = {};
               if (jDate.code == "success") {
                  sResule.url = "http://" + conf.fileServer + ":" + conf.fileServerPort + jDate.path;
                  sResule.original = fileName;
                  sResule.state = "SUCCESS";
               } else {
                  sResule.state = "Fail";
               }
               routeRes.end(JSON.stringify(sResule));
            });
         });
         req.on('error', (e) => {
            next(e);
            console.log(`请求遇到问题: ${e.message}`);
         });
         // 写入数据到请求主体
         req.write(sPostData);
         req.end();
      }
      
      var form = new formidable.IncomingForm();
      form.parse(routeReq, function (err, fields, files) {
      });
      form.on('file', function (name, file) {
         fs.readFile(file.path, function (err, data) {
            if (err) next(err);
            sentPicToServer(new Buffer(data).toString('base64'), file.name);
         });
      });
   }
}

/-----------------------------------2017121更新-------------------------------/

应网友要求,我在github提供源码如下

https://github.com/ShuangMuChengLi/vue.js_webpack_Ueditor

不使用jquery,采用vue.js

<template>
    <div class="wrap">
        <h1></h1>
        <a class="model" href="javascript:void(0)" @click="loadModel()">设置内容</a>
        <div id="editor" type="text/plain" style="height:500px;"></div>
    </div>
</template>

<script>
 var UE = require("../../ueditor/ueditor.all");

 export default {
        data () {
            return {

            }
        },
 watch: {

        },
 created:function () {

        },
 mounted:function () {
           this.ue = UE.getEditor('editor',{'autoHeightEnabled': false});
 },
 methods: {
           loadModel (){
                this.ue.setContent("内容")
           }
        },
 destroyUe(){
            UE.delEditor("editor");
 },
 }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
 @import "../../css/index";
</style>

/-----------------------------------20200116更新-------------------------------/

修改了一些新版谷歌浏览器不兼容的BUG,将JSONP、form+Iframe请求使用axios调用

因此要依赖axios

yarn add axios

https://github.com/ShuangMuChengLi/project-init/tree/ueditor

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值