1.首先,咱們定義一個名爲GetConfigServlet的Servlet,真實項目應該是一個Controller,同樣的,這個類就是加載後端配置文件類javascript
package com.ay.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.baidu.ueditor.ActionEnter; /** * 該類主要是獲取配置文件 * @author Ay * Servlet implementation class GetConfigServlet */ @WebServlet("/GetConfigServlet") public class GetConfigServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public GetConfigServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //這裏就是把controller.jsp代碼copy下來 request.setCharacterEncoding( "utf-8" ); response.setHeader("Content-Type" , "text/html"); String roolPath = request.getSession().getServletContext().getRealPath("/"); //記得把config.json放到/Test/WEB-INF/下 String configStr = new ActionEnter(request, roolPath).exec(); System.out.println(roolPath); response.getWriter().write(configStr); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
下面是個人代碼分佈圖片:php
2.修改ueditor.config,把serverUrl的路徑改成咱們本身寫的後端接口路徑,也就是GetConfigServlet類html
//原來 // 服務器統一請求接口路徑 , serverUrl: URL + "jsp/controller.jsp" //改成 , serverUrl: URL + "GetConfigServlet"
3.上面就能夠加載出富文本框了,這裏介紹一個js類loadconfig.js:前端
(function(){ UE.Editor.prototype.loadServerConfig = function(){ var me = this; setTimeout(function(){ try{ me.options.imageUrl && me.setOpt('serverUrl', me.options.imageUrl.replace(/^(.*[\/]).+([\.].+)$/, '$1controller$2')); var configUrl = me.getActionUrl('config'), isJsonp = utils.isCrossDomainUrl(configUrl); /* 發出ajax請求 */ me._serverConfigLoaded = false; configUrl && UE.ajax.request(configUrl,{ 'method': 'GET', 'dataType': isJsonp ? 'jsonp':'', 'onsuccess':function(r){ try { var config = isJsonp ? r:eval("("+r.responseText+")"); utils.extend(me.options, config); me.fireEvent('serverConfigLoaded'); me._serverConfigLoaded = true; } catch (e) { showErrorMsg(me.getLang('loadconfigFormatError')); } }, 'onerror':function(){ showErrorMsg(me.getLang('loadconfigHttpError')); } }); } catch(e){ showErrorMsg(me.getLang('loadconfigError')); } }); function showErrorMsg(msg) { console && console.error(msg); //me.fireEvent('showMessage', { // 'title': msg, // 'type': 'error' //}); } }; UE.Editor.prototype.isServerConfigLoaded = function(){ var me = this; return me._serverConfigLoaded || false; }; UE.Editor.prototype.afterConfigReady = function(handler){ if (!handler || !utils.isFunction(handler)) return; var me = this; var readyHandler = function(){ handler.apply(me, arguments); me.removeListener('serverConfigLoaded', readyHandler); }; if (me.isServerConfigLoaded()) { handler.call(me, 'serverConfigLoaded'); } else { me.addListener('serverConfigLoaded', readyHandler); } }; })();
4.但是有沒有發現一個問題,調用服務端的統一接口已經被加載配置文件給佔用了,接下來上傳文件接口沒有了,怎麼辦呢,怎麼辦呢,怎麼辦呢???java
其實UEditor官網在第五章已經講了,看第五章的:ajax
如何自定義請求地址
本文檔說明修改請求地址的方法。json
應用場景
ueditor 1.4.2+ 推薦使用惟一的請求地址,經過GET參數action指定不一樣請求類型。 但不少用戶都但願使用本身寫好的上傳地址,下面提供一種解決方法: 因爲全部ueditor請求都經過editor對象的getActionUrl方法獲取請求地址,能夠直接經過複寫這個方法實現,例子以下:後端
UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl; UE.Editor.prototype.getActionUrl = function(action) { if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage') { return 'http://a.b.com/upload.php'; } else if (action == 'uploadvideo') { return 'http://a.b.com/video.php'; } else { return this._bkGetActionUrl.call(this, action); } }
上面是官方文檔,只要覆蓋掉原型中的getActionUrl便可api
5.咱們首先再建立一個類:fileUploadServlet.Java,用於處理文件上傳的代碼瀏覽器
package com.ay.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class fileUploadServlet */ @WebServlet("/fileUploadServlet") public class fileUploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public fileUploadServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
其次修改config.jso配置文件,把imageActionName的值改成上傳文件的路徑,以下:
/* 上傳圖片配置項 */ "imageActionName": "fileUploadServlet", /* 執行上傳圖片的 action名稱 */
最後,咱們在simpleupload.html上添加以下代碼:
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> <title></title> <script type="text/javascript" charset="utf-8" src="../ueditor.config.js"></script> <script type="text/javascript" charset="utf-8" src="editor_api.js"></script> </head> <body> <h1>UEditor簡單功能</h1> <!--style給定寬度能夠影響編輯器的最終寬度--> <script type="text/plain" id="myEditor"> <p>這裏我能夠寫一些輸入提示</p> </script> <script type="text/javascript"> UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl; UE.getEditor('myEditor',{ //這裏能夠選擇本身須要的工具按鈕名稱,此處僅選擇以下五個 //toolbars:[['FullScreen','simpleupload','Source', 'Undo', 'Redo','Bold','test']], //focus時自動清空初始化時的內容 autoClearinitialContent:true, //關閉字數統計 wordCount:false, //關閉elementPath elementPathEnabled:false, //默認的編輯區域高度 initialFrameHeight:300 //更多其餘參數,請參考ueditor.config.js中的配置項 }); UE.Editor.prototype.getActionUrl = function(action) { //這裏很重要,很重要,很重要,要和配置中的imageActionName值同樣 if (action == 'fileUploadServlet') { //這裏調用後端咱們寫的圖片上傳接口 return 'http://localhost:8081/Test/fileUploadServlet'; }else{ return this._bkGetActionUrl.call(this, action); } } </script> </body> </html>
圖片上傳的類:
package com.ay.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class fileUploadServlet */ @WebServlet("/fileUploadServlet") public class fileUploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public fileUploadServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //這裏就是咱們項目中真實的代碼了 //文件上傳確定是post請求 System.out.println("--------圖片上傳成功---------------"); System.out.println("------------------------------"); System.out.println("--------圖片上傳成功-----------"); } }
寫到這裏基本就完了,但是你有沒有發現,有個問題
通常狀況下,咱們項目的上傳接口以及寫好了,且返回到前端的json數據也定了,但是Ueditor須要的json格式和咱們項目中返回的json數據不同,怎麼辦呢?
通常狀況下,咱們項目的上傳接口以及寫好了,且返回到前端的json數據也定了,但是Ueditor須要的json格式和咱們項目中返回的json數據不同,怎麼辦呢?
通常狀況下,咱們項目的上傳接口以及寫好了,且返回到前端的json數據也定了,但是Ueditor須要的json格式和咱們項目中返回的json數據不同,怎麼辦呢?
看下面:
首先,咱們看看Ueditor圖片上傳成功後,返回的json數據
{ "state": "SUCCESS", "original": "80px - \u526f\u672c (2).jpg", "size": "13252", "title": "1465731377326075274.jpg", "type": ".jpg", "url": "/ueditor/jsp/upload/image/20160612/1465731377326075274.jpg" }
也就是說,若是咱們調用本身的圖片上傳接口,返回的json數據改形成Ueditor須要的json數據便可,在哪裏改呢
在simpleupload.js的callback中
function callback(){ try{ var link, json, loader, body = (iframe.contentDocument || iframe.contentWindow.document).body, result = body.innerText || body.textContent || ''; //這裏result就是咱們真實項目返回的json數據 //很簡單寫個方法,把老的json變成Ueditor須要的json oldJson = (new Function("return " + result))(); //這個方法是我寫的,用來轉化 var json = changeDataToJson(json); link = me.options.imageUrlPrefix + json.url; if(json.state == 'SUCCESS' && json.url) { loader = me.document.getElementById(loadingId); loader.setAttribute('src', link); loader.setAttribute('_src', link); loader.setAttribute('title', json.title || ''); loader.setAttribute('alt', json.original || ''); loader.removeAttribute('id'); domUtils.removeClasses(loader, 'loadingclass'); } else { showErrorLoader && showErrorLoader(json.state); } }catch(er){ showErrorLoader && showErrorLoader(me.getLang('simpleupload.loadError')); } form.reset(); domUtils.un(iframe, 'load', callback); } /** 本身寫的方法,大家能夠本身去實現 **/ function changeDataToJson(json){ var object = {"original":'',"size":'', "state":'',"title":'',"type":'', "url":''}; var _json = json; //。。。。。本身真實項目的邏輯 //。。。。。本身真實項目的邏輯 return object; }
其實,寫到這裏基本就結束了,但是還有一個問題
就是,通常,咱們圖片上傳,會把圖片上傳到服務器的某個盤裏,好比:C盤 或者D盤,不太會把它放到項目部署目錄下,由於一旦項目從新部署,圖片就會消失
這就引起一個問題,先看下面能成功的上傳和顯示的圖片,注意到圖片是放到 項目的/ueditor/jsp/upload … 目錄下,因此沒問題
<img src="http://localhost:8081/Test//ueditor/jsp/upload/image/20160612/1465731377326075274.jpg" title="1465731377326075274.jpg" _src="http://localhost:8081/Test//ueditor/jsp/upload/image/20160612/1465731377326075274.jpg" alt="80px - 副本 (2).jpg">
但是,咱們真實項目是放到非tomcat目錄下,如C,D盤,這時候,是這樣的:
<img src="D:/upload/image/20160612/1465731377326075274.jpg" title="1465731377326075274.jpg" _src="http://localhost:8081/Test//ueditor/jsp/upload/image/20160612/1465731377326075274.jpg" alt="80px - 副本 (2).jpg">
若是是這樣的或,google瀏覽器會報:
解決方法是:
該方法是咱們真實項目的一個controller層,提供一個方法,得到圖片流
/** * 根據ID獲取圖片流 * * @param id * @param request * @param response * @throws IOException */ @RequestMapping(value = "/{id}/image", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public void image(@PathVariable("id") String id, HttpServletRequest request, HttpServletResponse response) throws IOException { SysAttachment sysAttachment = sysAttachmentService.findById(id); AssertUtils.checkResourceFound(sysAttachment); response.setContentType("image/x-png"); response.setCharacterEncoding("UTF-8"); File file = new File(sysAttachment.getPath()); BufferedImage image = ImageIO.read(file); ImageIO.write(image, sysAttachment.getType(), response.getOutputStream()); }
也就是說,繼續經過調用後端的接口,得到圖片
這時候,img便籤變成,下面的 「xxx/xxx/image」 就是真實項目的controller的映射路徑了
<img src="xxx/xxx/image" title="1465731377326075274.jpg" _src="http://localhost:8081/Test//ueditor/jsp/upload/image/20160612/1465731377326075274.jpg" alt="80px - 副本 (2).jpg">
好了,真的結束了…..
最後用一張圖片,表達下上面的邏輯: