Vue集成Ueditor的前后端实现

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/liujun03/article/details/84453287

对比其他的富文本编辑器,Ueditor的功能相对来说是最强的,对于在Vue中集成Ueditor想必还是有这个需求的。

下面具体说下如何在Vue中集成Ueditor以及在后端如何进行配置提供上传功能。

我对比了多个在网上找到的方法,也分别做了实验,其中感觉最简便的是Github上网友提供的插件:vue-ueditor-wrap,他借用Vue提供的语法糖实现了数据的双向绑定,不用你自己去getContent或setContent

Github地址为:vue-ueditor-wrap

首先做下准备工作,从Ueditor官网上下载Ueditor完整源码以及Jsp版本

在这里插入图片描述

Ueditor官网地址为: Ueditor

下载好之后,将Jsp版本解压,解压后文件夹改名为ueditor,将文件夹中的jsp目录删掉,之后将整个ueditor文件夹拷贝到Vue的public目录下,我是使用vue-cli3.0创建的项目,没有static目录只有public目录,项目结构如下:

在这里插入图片描述

这是前期的准备工作,做完之后,开始安装vue-ueditor-wrap插件:

npm install --save vue-ueditor-wrap

安装成功之后,就可以尝试使用了

下面是我的测试页面 Ueditor.vue

<template>
    <Card class="ueditor">
      <vue-ueditor-wrap v-model="content" :config="myConfig"></vue-ueditor-wrap>
      {{ content }}
    </Card>
</template>

<script>
  import VueUeditorWrap from 'vue-ueditor-wrap'
  export default {
    name: 'Ueditor',
    components: {VueUeditorWrap},
    data () {
      return {
        myConfig: {
          // 如果需要上传功能,找后端小伙伴要服务器接口地址
          // serverUrl: this.$config.baseUrl + 'ueditor/ueditorConfig',
          // serverUrl: 'http://localhost:8090/ueditor/ueditorConfig',
          // 你的UEditor资源存放的路径,相对于打包后的index.html
          UEDITOR_HOME_URL: '/ueditor/',
          // 编辑器不自动被内容撑高
          autoHeightEnabled: false,
          // 工具栏是否可以浮动
          autoFloatEnabled: false,
          // 初始容器高度
          initialFrameHeight: 340,
          // 初始容器宽度
          initialFrameWidth: '100%',
          // 关闭自动保存
          enableAutoSave: true
        },
        content: ''
      }
    }
  }
</script>

<style scoped>

</style>

步骤无外乎这几步:

  1. 引入VueUeditorWrap组件

    import VueUeditorWrap from 'vue-ueditor-wrap'

  2. 注册组件

    components: {VueUeditorWrap},

  3. v-model绑定数据

    <vue-ueditor-wrap v-model="content" :config="myConfig"></vue-ueditor-wrap>

其中config是你根据自己的需求修改配置,

其中的UEDITOR_HOME_URL: '/ueditor/',这个配置很重要,一定得写对

这些都完成之后,就可以在页面上测试一番了。

在这里插入图片描述

这样的话基本功能就全都出来了,下面介绍下如何配合后台实现上传功能。

在前后分离之前用过Ueditor的就知道,要使用上传功能,首先后台得提供配置文件,之后就是提供相应的上传方法了,下面就上传图片做个介绍,其他的上传操作都是类似的。

在前面的准备工作中,我们把Ueditor的源码下载下来了,我们找到其中的这个jar包,将之解压后全部复制到后台工程中,其他的jar包在pom文件引入就可以了:

在这里插入图片描述

在这里插入图片描述

注意到这里资源目录下有个config.json文件,这是Ueditor上传功能所需的配置文件,这个文件在Ueditor-jsp版本的jsp目录下,找到将之复制到资源目录中。

在这里插入图片描述

现在将所需文件都复制好之后,就可以来修改源码来提供上传功能了。

原来Ueditor是通过访问上面截图中的controller.jsp文件来初始化配置文件以及进行上传操作的,我们现在将之用代码进行替换。

下面看一下我写的提供配置文件以及提供上传图片功能的源码:

package com.baiding.vue.controller;

import com.baidu.ueditor.ActionEnter;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: BaiDing
 * @Date: 2018/8/30 11:58
 * @Email: [email protected]
 */
@RestController
public class UeditorController {

    private static final Logger logger = LoggerFactory.getLogger(UeditorController.class);

    @RequestMapping("/ueditor/ueditorConfig")
    public void ueditorConfig(HttpServletRequest request, HttpServletResponse response, MultipartFile upfile) {

        response.setContentType("application/json");
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        try {
            String exec = "";
            String actionType = request.getParameter("action");
            if("uploadimage".equals(actionType) && !upfile.isEmpty()){
                // 做图片上传操作
                exec = uploadImage(upfile);

            }else{
                request.setCharacterEncoding( "utf-8" );
                exec = new ActionEnter(request, rootPath).exec();
            }
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            logger.error("UeditorController#ueditorConfig exception:",e);
        }
    }

    private String uploadImage(MultipartFile file) {
        JSONObject jsonResult = null;
        try {
            String fileName = file.getOriginalFilename();
            String extraName = fileName.substring(fileName.lastIndexOf("."));
            // 这里就是上传图片的具体逻辑了,原本是通过fastdfs来上传图片的,这里就简单生成个字符串假装上传成功了吧
//            String url = FastdfsUtil.upload(file.getBytes(), file.getOriginalFilename());
            String str = UUID.randomUUID().toString();
            String url = "http://dfs.image.com/"+str+".png ";
            jsonResult = new JSONObject(resultMap("SUCCESS",url,file.getSize(),fileName,fileName,extraName));

        } catch (Exception e) {
            logger.warn("UeditorController#uploadImage exception:",e);
            jsonResult = new JSONObject(resultMap("文件上传失败","",0,"","",""));
        }
        return jsonResult.toString();
    }

    //{"state": "SUCCESS","original": "111.jpg","size": "124147","title": "1535961757878095151.jpg","type": ".jpg","url": "/1535961757878095151.jpg"}

    private Map<String,Object> resultMap(String state, String url, long size, String title, String original, String type){
        Map<String ,Object> result = new HashMap<>();
        result.put("state",state);
        result.put("original",original);
        result.put("size",size);
        result.put("title",title);
        result.put("type",type);
        result.put("url", url);
        return result;
    }

}

Ueditor访问后台时会在url后面带上操作类型即action这个参数,来表明它是要获取配置文件还是要上传图片或者上传视频的。所以我通过对这个action来判断接下来的操作:

String actionType = request.getParameter("action");
if("uploadimage".equals(actionType) && !upfile.isEmpty()){
    // 做图片上传操作
    exec = uploadImage(upfile);

}else{
    request.setCharacterEncoding( "utf-8" );
    exec = new ActionEnter(request, rootPath).exec();
}

如果是上传图片的话就执行自定义操作,如果是获取配置文件的话就去上面复制进来的源码中执行。

上面我们将配置文件复制到了资源目录下,所以接下来修改下获取配置文件的源码,很简单的:

找到ConfigManager文件:

在这里插入图片描述

之后在156行左右找到:

String configContent = this.readFile( this.getConfigPath() );

将之替换为:

String configJsonPath = null;
try {
    configJsonPath = this.getClass().getClassLoader().getResource("config.json").toURI().getPath();
} catch (URISyntaxException e) {
    e.printStackTrace();
}
String configContent = this.readFile( configJsonPath );

在这里插入图片描述

按上述一步步操作之后,后台关于获取上传配置文件以及提供上传图片功能就完成了,接下来在前台配置一下访问Url就可以了。

在这里插入图片描述

这个serverurl就是Ueditor访问后台的路径了,将之配置正确之后,就可以测试上传图片功能了。

在这里插入图片描述

这是上传成功之后得到的url.

单图上传功能的话你必须得在前端做这个serverUrl的代理,否则会报上传失败的错误

题外话:项目得在线上使用,单图上传功能在测试的时候可以通过在前端配置代理解决跨域问题,但是在线上的话这个跨域问题由于单图上传的逻辑暂时得不到解决,所以我把单图上传按钮给去掉了,要上传图片就使用多图上传。

下面推荐一下我自己写的一个完整的Vue后台管理项目,里面基本后台需要的功能都有的:

Vue后台管理

猜你喜欢

转载自blog.csdn.net/liujun03/article/details/84453287
今日推荐