springboot下怎么实现ueditor上传功能

小编给大家分享一下springboot下怎么实现ueditor上传功能,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

前言

本文主要写的是:springboot下ueditor上传功能的实现及遇到的一些问题的处理

整体项目结构展示

springboot下怎么实现ueditor上传功能

Springboot整合ueditor及上传功能实现的具体步骤

1、下载ueditor-1.4.3.3

这个在官网下载就行,不过貌似utf-8版本的没有资源了,源码版的下了几次都中断了,最终我是从第三方下的

2、新建一个测试页面

ueditor的根目录下有一个index.html,用它就行,源码如下

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title>完整demo</title>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
  <!-- 将config.json放在保存文件的根目录位置 -->
  <script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script>
  <script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.js"> </script>
</head>
<body>
<div>
  <h2>UEditor演示</h2>
  <script id="editor" type="text/plain" ></script>
</div>
<div id="btns">
  <div>
    <button οnclick="getAllHtml()">获得整个html的内容</button>
    <button οnclick="getContent()">获得内容</button>
    <button οnclick="setContent()">写入内容</button>
    <button οnclick="setContent(true)">追加内容</button>
    <button οnclick="getContentTxt()">获得纯文本</button>
    <button οnclick="getPlainTxt()">获得带格式的纯文本</button>
    <button οnclick="hasContent()">判断是否有内容</button>
    <button οnclick="setFocus()">使编辑器获得焦点</button>
    <button οnmοusedοwn="isFocus(event)">编辑器是否获得焦点</button>
    <button οnmοusedοwn="setblur(event)" >编辑器失去焦点</button>
  </div>
  <div>
    <button οnclick="getText()">获得当前选中的文本</button>
    <button οnclick="insertHtml()">插入给定的内容</button>
    <button id="enable" οnclick="setEnabled()">可以编辑</button>
    <button οnclick="setDisabled()">不可编辑</button>
    <button οnclick=" UE.getEditor('editor').setHide()">隐藏编辑器</button>
    <button οnclick=" UE.getEditor('editor').setShow()">显示编辑器</button>
    <button οnclick=" UE.getEditor('editor').setHeight(300)">设置高度为300默认关闭了自动长高</button>
  </div>
  <div>
    <button οnclick="getLocalData()" >获取草稿箱内容</button>
    <button οnclick="clearLocalData()" >清空草稿箱</button>
  </div>
</div>
<div>
  <button οnclick="createEditor()">
  创建编辑器</button>
  <button οnclick="deleteEditor()">
  删除编辑器</button>
</div>
<script type="text/javascript">
  //实例化编辑器
  //建议使用工厂方法getEditor创建和引用编辑器实例,如果在某个闭包下引用该编辑器,直接调用UE.getEditor('editor')就能拿到相关的实例
  var ue = UE.getEditor('editor');
  function isFocus(e){
    alert(UE.getEditor('editor').isFocus());
    UE.dom.domUtils.preventDefault(e)
  }
  function setblur(e){
    UE.getEditor('editor').blur();
    UE.dom.domUtils.preventDefault(e)
  }
  function insertHtml() {
    var value = prompt('插入html代码', '');
    UE.getEditor('editor').execCommand('insertHtml', value)
  }
  function createEditor() {
    enableBtn();
    UE.getEditor('editor');
  }
  function getAllHtml() {
    alert(UE.getEditor('editor').getAllHtml())
  }
  function getContent() {
    var arr = [];
    arr.push("使用editor.getContent()方法可以获得编辑器的内容");
    arr.push("内容为:");
    arr.push(UE.getEditor('editor').getContent());
    alert(arr.join("\n"));
  }
  function getPlainTxt() {
    var arr = [];
    arr.push("使用editor.getPlainTxt()方法可以获得编辑器的带格式的纯文本内容");
    arr.push("内容为:");
    arr.push(UE.getEditor('editor').getPlainTxt());
    alert(arr.join('\n'))
  }
  function setContent(isAppendTo) {
    var arr = [];
    arr.push("使用editor.setContent('欢迎使用ueditor')方法可以设置编辑器的内容");
    UE.getEditor('editor').setContent('欢迎使用ueditor', isAppendTo);
    alert(arr.join("\n"));
  }
  function setDisabled() {
    UE.getEditor('editor').setDisabled('fullscreen');
    disableBtn("enable");
  }
 
  function setEnabled() {
    UE.getEditor('editor').setEnabled();
    enableBtn();
  }
 
  function getText() {
    //当你点击按钮时编辑区域已经失去了焦点,如果直接用getText将不会得到内容,所以要在选回来,然后取得内容
    var range = UE.getEditor('editor').selection.getRange();
    range.select();
    var txt = UE.getEditor('editor').selection.getText();
    alert(txt)
  }
 
  function getContentTxt() {
    var arr = [];
    arr.push("使用editor.getContentTxt()方法可以获得编辑器的纯文本内容");
    arr.push("编辑器的纯文本内容为:");
    arr.push(UE.getEditor('editor').getContentTxt());
    alert(arr.join("\n"));
  }
  function hasContent() {
    var arr = [];
    arr.push("使用editor.hasContents()方法判断编辑器里是否有内容");
    arr.push("判断结果为:");
    arr.push(UE.getEditor('editor').hasContents());
    alert(arr.join("\n"));
  }
  function setFocus() {
    UE.getEditor('editor').focus();
  }
  function deleteEditor() {
    disableBtn();
    UE.getEditor('editor').destroy();
  }
  function disableBtn(str) {
    var div = document.getElementById('btns');
    var btns = UE.dom.domUtils.getElementsByTagName(div, "button");
    for (var i = 0, btn; btn = btns[i++];) {
      if (btn.id == str) {
        UE.dom.domUtils.removeAttributes(btn, ["disabled"]);
      } else {
        btn.setAttribute("disabled", "true");
      }
    }
  }
  function enableBtn() {
    var div = document.getElementById('btns');
    var btns = UE.dom.domUtils.getElementsByTagName(div, "button");
    for (var i = 0, btn; btn = btns[i++];) {
      UE.dom.domUtils.removeAttributes(btn, ["disabled"]);
    }
  }
 
  function getLocalData () {
    alert(UE.getEditor('editor').execCommand( "getlocaldata" ));
  }
 
  function clearLocalData () {
    UE.getEditor('editor').execCommand( "clearlocaldata" );
    alert("已清空草稿箱")
  }
</script>
</body>
</html>

3、引入上传所需的jar包

<dependency>
 <groupId>com.gitee.qdbp.thirdparty</groupId>
 <artifactId>ueditor</artifactId>
 <version>1.4.3.3</version>
</dependency>
<dependency>
 <groupId>commons-codec</groupId>
 <artifactId>commons-codec</artifactId>
</dependency>
<dependency>
 <groupId>commons-fileupload</groupId>
 <artifactId>commons-fileupload</artifactId>
 <version>1.3.1</version>
</dependency>
<dependency>
 <groupId>commons-io</groupId>
 <artifactId>commons-io</artifactId>
 <version>2.5</version>
 <scope>compile</scope>
</dependency>
<dependency>
 <groupId>org.json</groupId>
 <artifactId>json</artifactId>
</dependency>

4、新建上传文件保存目录文件夹,如下

springboot下怎么实现ueditor上传功能

其中的config.json是从ueditor-1.4.3.3的文件夹里拷过来,因为我发现默认上传文件路径就是config.json所在目录,而且springboot下我试了配置imagePathFormat并没有什么用。

5、新建UeditorController

用于读取ueditor.json配置文件,同时实现上传方法(当然这里我们直接使用了ueditor.jar的上传,因此显得很简单,但如果要我们自己写那就有一堆代码量了)

import com.baidu.ueditor.ActionEnter;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
 
/**
 * 百度富文本编辑器
 * 描述1:config.json中配置的如图片大小限制(imageMaxSize)文件类型等在页面js中已经验证过了,后台不需要在处理
 * 描述2:使用ueditor.jar的话就不需要自己
 * 描述3:config.json中imageUrlPrefix配置举例:"imageUrlPrefix": "/fileupload/ueditor"
 * 描述3:config.json中imagePathFormat配置举例:"imagePathFormat": "/image/{yyyy}{mm}{dd}/{time}{rand:6}"
 * 描述4:imageUrlPrefix + imagePathFormat 为上传文件的访问路径
 *
 * zkh
 * 2019年11月14日 9:09
 */
@Controller
public class UeditorController {
 
  // /ueditor/jsp/config.json文件所在的父目录,上传文件默认根目录为config.json文件所在目录
  private String configJsonParentPath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/fileupload/ueditor";
 
  /**
   * UEditor初始化时会以get方式请求serverUrl地址,并且需要在action=config时返回UEditor配置文件信息
   * 描述:使用ueditor.jar包中的ActionEnter的话,就不需要自己再去实现其上传功能,因为ActionEnter已经帮我们实现了
   */
  @RequestMapping("ueditor")
  public void getEditorConfig(HttpServletRequest request, HttpServletResponse response, String action) {
    response.setContentType("application/json");
    try {
      String exec = new ActionEnter(request, configJsonParentPath).exec();
      if(action!=null && (action.equals("listfile") || action.equals("listimage"))) {
        exec = exec.replace(configJsonParentPath.substring(1), "/");
      }
      PrintWriter writer = response.getWriter();
      writer.write(exec);
      writer.flush();
      writer.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

注意看注释

6、接着,我们需要将ueditor.config.js中的serverUrl配置为我们在第5步的那个controller,如下

springboot下怎么实现ueditor上传功能

7、最后还要在config.json中配置下我们上传的具体细节,下面以图片上传为例

/* 上传图片配置项 */
  "imageActionName": "uploadimage", /* 执行上传图片的action名称(举例:http://localhost:8080/ueditor?action=uploadimage) */
  "imageFieldName": "upfile", /* 提交的图片表单名称 */
  "imageMaxSize": 2048000, /* 上传大小限制,单位B */
  "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
  "imageCompressEnable": true, /* 是否压缩图片,默认是true */
  "imageCompressBorder": 1600, /* 图片压缩最长边限制 */
  "imageInsertAlign": "none", /* 插入的图片浮动方式 */
  /* imageUrlPrefix + imagePathFormat 为当前文件的访问路径 */
  "imageUrlPrefix": "/fileupload/ueditor", /* 图片访问路径前缀 */
  /* imagePathFormat默认以当前config.json所在的目录为根目录 */
  "imagePathFormat": "/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* (注意:默认以当前config.json所在的目录为根目录)上传保存路径,可以自定义保存路径和文件名格式 */
                /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */
                /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */
                /* {time} 会替换成时间戳 */
                /* {yyyy} 会替换成四位年份 */
                /* {yy} 会替换成两位年份 */
                /* {mm} 会替换成两位月份 */
                /* {dd} 会替换成两位日期 */
                /* {hh} 会替换成两位小时 */
                /* {ii} 会替换成两位分钟 */
                /* {ss} 会替换成两位秒 */
                /* 非法字符 \ : * ? " < > | */
                /* 具请体看线上文档: fex.baidu.com/ueditor/#use-format_upload_filename */

这里我们需要关注重点理解的是 imageUrlPrefix 、imagePathFormat

1) 域名 + imageUrlPrefix + imagePathFormat 为当前文件的访问路径;

2)imageUrlPrefix是图片访问路径前缀,例如:http://localhost:8080/fileupload/ueditor,imageUrlPrefix就是其中的“/fileupload/ueditor”;

3)imagePathFormat是以imageUrlPrefix为根路径的文件存放的具体路径,例如:

http://localhost:8080/fileupload/ueditor/image/20190202/121222.jpg,imagePathFormat就是其中的“/image/20190202/121222.jpg”;

4)剩下其他参数就很明显了。

7、可能会遇到的问题

1、明明配置的文件最大为2048000,但是文件只有1M多点后台报错了?

解决:这是因为默认开启了springboot的上传,在application.properties中 spring.servlet.multipart.enabled=false 就可以了,或者也可以跳下它的默认最大值 spring.servlet.multipart.max-file-size=1MB,具体如下图:

springboot下怎么实现ueditor上传功能

2、明明修改了imagePathFormat,单还是保存在了原始的路径下?

解决:直接将config.json文件放到了我想保存文件的位置即可。

3、在线管理图片无法显示?

解决:在我们上面的UeditorController中其实已经解决了,就是当action=listfile或者action=listimage时将new ActionEnter(request, configJsonParentPath).exec()得到的字符串中的configJsonParentPath路径替换为空字符串即可,如下

springboot下怎么实现ueditor上传功能

最后启动服务,打开http://localhost:8080/ueditor/index.html页面测试,效果如下图:

springboot下怎么实现ueditor上传功能

springboot下怎么实现ueditor上传功能

看完了这篇文章,相信你对“springboot下怎么实现ueditor上传功能”有了一定的了解,如果想了解更多相关知识,欢迎关注行业资讯频道,感谢各位的阅读!