溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

springboot下怎么實(shí)現(xiàn)ueditor上傳功能

發(fā)布時(shí)間:2021-06-04 15:10:23 來(lái)源:億速云 閱讀:121 作者:小新 欄目:編程語(yǔ)言

小編給大家分享一下springboot下怎么實(shí)現(xiàn)ueditor上傳功能,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

前言

本文主要寫(xiě)的是:springboot下ueditor上傳功能的實(shí)現(xiàn)及遇到的一些問(wèn)題的處理

整體項(xiàng)目結(jié)構(gòu)展示

springboot下怎么實(shí)現(xiàn)ueditor上傳功能

Springboot整合ueditor及上傳功能實(shí)現(xiàn)的具體步驟

1、下載ueditor-1.4.3.3

這個(gè)在官網(wǎng)下載就行,不過(guò)貌似utf-8版本的沒(méi)有資源了,源碼版的下了幾次都中斷了,最終我是從第三方下的

2、新建一個(gè)測(cè)試頁(yè)面

ueditor的根目錄下有一個(gè)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()">獲得整個(gè)html的內(nèi)容</button>
    <button οnclick="getContent()">獲得內(nèi)容</button>
    <button οnclick="setContent()">寫(xiě)入內(nèi)容</button>
    <button οnclick="setContent(true)">追加內(nèi)容</button>
    <button οnclick="getContentTxt()">獲得純文本</button>
    <button οnclick="getPlainTxt()">獲得帶格式的純文本</button>
    <button οnclick="hasContent()">判斷是否有內(nèi)容</button>
    <button οnclick="setFocus()">使編輯器獲得焦點(diǎn)</button>
    <button οnmοusedοwn="isFocus(event)">編輯器是否獲得焦點(diǎn)</button>
    <button οnmοusedοwn="setblur(event)" >編輯器失去焦點(diǎn)</button>
  </div>
  <div>
    <button οnclick="getText()">獲得當(dāng)前選中的文本</button>
    <button οnclick="insertHtml()">插入給定的內(nèi)容</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)">設(shè)置高度為300默認(rèn)關(guān)閉了自動(dòng)長(zhǎng)高</button>
  </div>
  <div>
    <button οnclick="getLocalData()" >獲取草稿箱內(nèi)容</button>
    <button οnclick="clearLocalData()" >清空草稿箱</button>
  </div>
</div>
<div>
  <button οnclick="createEditor()">
  創(chuàng)建編輯器</button>
  <button οnclick="deleteEditor()">
  刪除編輯器</button>
</div>
<script type="text/javascript">
  //實(shí)例化編輯器
  //建議使用工廠方法getEditor創(chuàng)建和引用編輯器實(shí)例,如果在某個(gè)閉包下引用該編輯器,直接調(diào)用UE.getEditor('editor')就能拿到相關(guān)的實(shí)例
  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()方法可以獲得編輯器的內(nèi)容");
    arr.push("內(nèi)容為:");
    arr.push(UE.getEditor('editor').getContent());
    alert(arr.join("\n"));
  }
  function getPlainTxt() {
    var arr = [];
    arr.push("使用editor.getPlainTxt()方法可以獲得編輯器的帶格式的純文本內(nèi)容");
    arr.push("內(nèi)容為:");
    arr.push(UE.getEditor('editor').getPlainTxt());
    alert(arr.join('\n'))
  }
  function setContent(isAppendTo) {
    var arr = [];
    arr.push("使用editor.setContent('歡迎使用ueditor')方法可以設(shè)置編輯器的內(nèi)容");
    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() {
    //當(dāng)你點(diǎn)擊按鈕時(shí)編輯區(qū)域已經(jīng)失去了焦點(diǎn),如果直接用getText將不會(huì)得到內(nèi)容,所以要在選回來(lái),然后取得內(nèi)容
    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()方法可以獲得編輯器的純文本內(nèi)容");
    arr.push("編輯器的純文本內(nèi)容為:");
    arr.push(UE.getEditor('editor').getContentTxt());
    alert(arr.join("\n"));
  }
  function hasContent() {
    var arr = [];
    arr.push("使用editor.hasContents()方法判斷編輯器里是否有內(nèi)容");
    arr.push("判斷結(jié)果為:");
    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下怎么實(shí)現(xiàn)ueditor上傳功能

其中的config.json是從ueditor-1.4.3.3的文件夾里拷過(guò)來(lái),因?yàn)槲野l(fā)現(xiàn)默認(rèn)上傳文件路徑就是config.json所在目錄,而且springboot下我試了配置imagePathFormat并沒(méi)有什么用。

5、新建UeditorController

用于讀取ueditor.json配置文件,同時(shí)實(shí)現(xiàn)上傳方法(當(dāng)然這里我們直接使用了ueditor.jar的上傳,因此顯得很簡(jiǎn)單,但如果要我們自己寫(xiě)那就有一堆代碼量了)

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)文件類型等在頁(yè)面js中已經(jīng)驗(yàn)證過(guò)了,后臺(tái)不需要在處理
 * 描述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 為上傳文件的訪問(wèn)路徑
 *
 * zkh
 * 2019年11月14日 9:09
 */
@Controller
public class UeditorController {
 
  // /ueditor/jsp/config.json文件所在的父目錄,上傳文件默認(rèn)根目錄為config.json文件所在目錄
  private String configJsonParentPath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/fileupload/ueditor";
 
  /**
   * UEditor初始化時(shí)會(huì)以get方式請(qǐng)求serverUrl地址,并且需要在action=config時(shí)返回UEditor配置文件信息
   * 描述:使用ueditor.jar包中的ActionEnter的話,就不需要自己再去實(shí)現(xiàn)其上傳功能,因?yàn)锳ctionEnter已經(jīng)幫我們實(shí)現(xiàn)了
   */
  @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配置為我們?cè)诘?步的那個(gè)controller,如下

springboot下怎么實(shí)現(xiàn)ueditor上傳功能

7、最后還要在config.json中配置下我們上傳的具體細(xì)節(jié),下面以圖片上傳為例

/* 上傳圖片配置項(xiàng) */
  "imageActionName": "uploadimage", /* 執(zhí)行上傳圖片的action名稱(舉例:http://localhost:8080/ueditor?action=uploadimage) */
  "imageFieldName": "upfile", /* 提交的圖片表單名稱 */
  "imageMaxSize": 2048000, /* 上傳大小限制,單位B */
  "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上傳圖片格式顯示 */
  "imageCompressEnable": true, /* 是否壓縮圖片,默認(rèn)是true */
  "imageCompressBorder": 1600, /* 圖片壓縮最長(zhǎng)邊限制 */
  "imageInsertAlign": "none", /* 插入的圖片浮動(dòng)方式 */
  /* imageUrlPrefix + imagePathFormat 為當(dāng)前文件的訪問(wèn)路徑 */
  "imageUrlPrefix": "/fileupload/ueditor", /* 圖片訪問(wèn)路徑前綴 */
  /* imagePathFormat默認(rèn)以當(dāng)前config.json所在的目錄為根目錄 */
  "imagePathFormat": "/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* (注意:默認(rèn)以當(dāng)前config.json所在的目錄為根目錄)上傳保存路徑,可以自定義保存路徑和文件名格式 */
                /* {filename} 會(huì)替換成原文件名,配置這項(xiàng)需要注意中文亂碼問(wèn)題 */
                /* {rand:6} 會(huì)替換成隨機(jī)數(shù),后面的數(shù)字是隨機(jī)數(shù)的位數(shù) */
                /* {time} 會(huì)替換成時(shí)間戳 */
                /* {yyyy} 會(huì)替換成四位年份 */
                /* {yy} 會(huì)替換成兩位年份 */
                /* {mm} 會(huì)替換成兩位月份 */
                /* {dd} 會(huì)替換成兩位日期 */
                /* {hh} 會(huì)替換成兩位小時(shí) */
                /* {ii} 會(huì)替換成兩位分鐘 */
                /* {ss} 會(huì)替換成兩位秒 */
                /* 非法字符 \ : * ? " < > | */
                /* 具請(qǐng)?bào)w看線上文檔: fex.baidu.com/ueditor/#use-format_upload_filename */

這里我們需要關(guān)注重點(diǎn)理解的是 imageUrlPrefix 、imagePathFormat

1) 域名 + imageUrlPrefix + imagePathFormat 為當(dāng)前文件的訪問(wèn)路徑;

2)imageUrlPrefix是圖片訪問(wèn)路徑前綴,例如: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)剩下其他參數(shù)就很明顯了。

7、可能會(huì)遇到的問(wèn)題

1、明明配置的文件最大為2048000,但是文件只有1M多點(diǎn)后臺(tái)報(bào)錯(cuò)了?

解決:這是因?yàn)槟J(rèn)開(kāi)啟了springboot的上傳,在application.properties中 spring.servlet.multipart.enabled=false 就可以了,或者也可以跳下它的默認(rèn)最大值 spring.servlet.multipart.max-file-size=1MB,具體如下圖:

springboot下怎么實(shí)現(xiàn)ueditor上傳功能

2、明明修改了imagePathFormat,單還是保存在了原始的路徑下?

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

3、在線管理圖片無(wú)法顯示?

解決:在我們上面的UeditorController中其實(shí)已經(jīng)解決了,就是當(dāng)action=listfile或者action=listimage時(shí)將new ActionEnter(request, configJsonParentPath).exec()得到的字符串中的configJsonParentPath路徑替換為空字符串即可,如下

springboot下怎么實(shí)現(xiàn)ueditor上傳功能

最后啟動(dòng)服務(wù),打開(kāi)http://localhost:8080/ueditor/index.html頁(yè)面測(cè)試,效果如下圖:

springboot下怎么實(shí)現(xiàn)ueditor上傳功能

springboot下怎么實(shí)現(xiàn)ueditor上傳功能

看完了這篇文章,相信你對(duì)“springboot下怎么實(shí)現(xiàn)ueditor上傳功能”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI