Java maven專案整合ueditor(百度本編輯器)外掛詳解
阿新 • • 發佈:2019-02-10
相信很多專案都要用到類似的功能,ueditor是一個非常強大的外掛,當然也有直接整合好的直接引用就行了。在這裡講一下百度編輯器的整合過程,本人是走了好多彎路,在這裡希望各位開發的朋友少走些彎路,節約開發時間。
1,首先需要下載ueditor包 我下載的是 ueditor1_4_3_3-utf8-jsp ,然後引入專案裡面 把相關的js和css 配置到配置檔案中
2,第一步實現了 ,那麼就要在jsp頁面顯示出來。很簡單
<div id="editor" style="width:794px;height:340px;"></div> <script type="text/javascript"> var ue = UE.getEditor('editor'); </script>
3,難點在於圖片的上傳,以及各種配置
找到jsp資料夾裡面config.json ,開啟需要改兩項 imageActionName , imagePathFormat
imageActionName -》執行上傳圖片的action名稱/* 上傳圖片配置項 */ "imageActionName": "uploadImage", /* 執行上傳圖片的action名稱 */ "imageFieldName": "upfile", /* 提交的圖片表單名稱 */ "imageMaxSize": 2048000, /* 上傳大小限制,單位B */ "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上傳圖片格式顯示 */ "imageCompressEnable": true, /* 是否壓縮圖片,預設是true */ "imageCompressBorder": 1600, /* 圖片壓縮最長邊限制 */ "imageInsertAlign": "none", /* 插入的圖片浮動方式 */ "imageUrlPrefix": "", /* 圖片訪問路徑字首 */ "imagePathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳儲存路徑,可以自定義儲存路徑和檔名格式 */ /* {filename} 會替換成原檔名,配置這項需要注意中文亂碼問題 */ /* {rand:6} 會替換成隨機數,後面的數字是隨機數的位數 */ /* {time} 會替換成時間戳 */ /* {yyyy} 會替換成四位年份 */ /* {yy} 會替換成兩位年份 */ /* {mm} 會替換成兩位月份 */ /* {dd} 會替換成兩位日期 */ /* {hh} 會替換成兩位小時 */ /* {ii} 會替換成兩位分鐘 */ /* {ss} 會替換成兩位秒 */ /* 非法字元 \ : * ? " < > | */ /* 具請體看線上文件: fex.baidu.com/ueditor/#use-format_upload_filename */
imagePathFormat-》上傳儲存路徑,可以自定義儲存路徑和檔名格式
4,修改 ueditor.config.js 自定義編輯器的功能
修改 toolbars/** * 編輯器資原始檔根路徑。它所表示的含義是:以編輯器例項化頁面為當前路徑,指向編輯器資原始檔(即dialog等資料夾)的路徑。 * 鑑於很多同學在使用編輯器的時候出現的種種路徑問題,此處強烈建議大家使用"相對於網站根目錄的相對路徑"進行配置。 * "相對於網站根目錄的相對路徑"也就是以斜槓開頭的形如"/myProject/ueditor/"這樣的路徑。 * 如果站點中有多個不在同一層級的頁面需要例項化編輯器,且引用了同一UEditor的時候,此處的URL可能不適用於每個頁面的編輯器。 * 因此,UEditor提供了針對不同頁面的編輯器可單獨配置的根路徑,具體來說,在需要例項化編輯器的頁面最頂部寫上如下程式碼即可。當然,需要令此處的URL等於對應的配置。 * window.UEDITOR_HOME_URL = "/xxxx/xxxx/"; */ var URL = window.UEDITOR_HOME_URL || getUEBasePath(); /** * 配置項主體。注意,此處所有涉及到路徑的配置別遺漏URL變數。 */ window.UEDITOR_CONFIG = { //為編輯器例項新增一個路徑,這個不能被註釋 UEDITOR_HOME_URL: URL // 伺服器統一請求介面路徑 , serverUrl: URL + "jsp/controller.jsp" //工具欄上的所有的功能按鈕和下拉框,可以在new編輯器的例項時選擇自己需要的重新定義 , toolbars: [[ 'bold', 'italic', 'underline', 'fontborder', 'strikethrough', '|', 'forecolor', 'backcolor', '|', 'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'fontfamily', 'fontsize', '|', 'indent', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'inserttable', '|','simpleupload','imagenone', 'imageleft', 'imageright', 'imagecenter' ]]
5,Java程式碼 上傳圖片 ,ueditor需要特定的返回值,title,original,size,state,type,url
controller裡面定義名稱和config.json裡面imageActionName定義的一樣,@RequestMapping("uploadImage")
@ResponseBody
@RequestMapping("uploadImage")
public Map<String,String> uploadImage(@RequestParam("upfile") CommonsMultipartFile upfile,HttpServletRequest request,Model model) throws Exception{
//得到路徑 C:/tomcat/webapps/testDemo/
String rootPath = request.getSession().getServletContext().getRealPath("/");
rootPath = rootPath.replaceAll("\\\\", "/");
String path = rootPath + "/ueditor/jsp/upload/image";
File f = new File(path);
if (!f.exists()) {
f.mkdirs();
}
FileItem item = upfile.getFileItem();
//檔案路徑
String pathFileName = item.getName();
//位元組數
long l = item.getSize();
String fileSize = Long.toString(l);
//檔名
int start = pathFileName.lastIndexOf("\\");
String fileName = pathFileName.substring(start + 1);
//字尾 .jpg
int indexName = fileName.lastIndexOf('.');
String subName = fileName.substring(indexName);
//新檔名
String nowName = new SimpleDateFormat("yyMMddHHmmss").format(new Date()) +"_"+ fileName;
item.write(new File(path, nowName));
String strBackUrl = "http://" + request.getServerName() //伺服器地址
+ ":"
+ request.getServerPort() //埠號
+ request.getContextPath(); //專案名稱
Map<String,String> map = new HashMap<String,String >();
//檔案原名稱
map.put("title", nowName);
//現在檔名稱
map.put("original", fileName);
//檔案大小(位元組數)
map.put("size", fileSize);
//是否上傳成功
map.put("state", "SUCCESS");
//檔案型別 .+字尾名
map.put("type", subName);
//檔案路徑
map.put("url", strBackUrl+"/ueditor/jsp/upload/image/"+nowName);
return map;
}
然後jsp裡面需要調 uploadImage
UE.Editor.prototype._bkGetActionUrl ? "" : UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
UE.Editor.prototype.getActionUrl = function(action) {
//這裡很重要,很重要,很重要,要和配置中的imageActionName值一樣
if (action == 'uploadImage'){
//這裡呼叫後端我們寫的圖片上傳介面
return '${ctx}/sys/upload/uploadImage';
}else{
return this._bkGetActionUrl.call(this, action);
}
}
這樣圖片就在編輯器裡面顯示出來了
6,儲存到資料庫裡是帶有標籤的text ,在這之前要把裡面圖片的路徑替換成伺服器的路徑
private final static Pattern ATTR_PATTERN = Pattern.compile("<img[^<>]*?\\ssrc=['\"]?(.*?)['\"]?\\s.*?>",Pattern.CASE_INSENSITIVE);
if (StringUtils.isEmpty(information.getId())) {
information.setId(IdGenerator.uuid());
//得到ueditor內的內容
String content = request.getParameter("editorValue");
Matcher matcher = ATTR_PATTERN.matcher(content);
List<String> piclist = new ArrayList<String>();
while (matcher.find()) {
piclist.add(matcher.group(1));
}
if(piclist.size() == 0){
information.setInfoText(content);
informationService.addInformation(information,user);
}else{
String newPicPath = "";
String str = "";
for (String string : piclist) {
//得到路徑名/ueditor/jsp/upload/image/....
str = string.substring(string.indexOf("/ueditor"));
//得到存圖片/ueditor/jsp/upload/image/....的專案路徑
String rootPath = request.getSession().getServletContext().getRealPath("/");
rootPath = rootPath.replaceAll("\\\\", "/");
//本地圖片的路徑
String picturePath = rootPath+str;
String folder = UserFileController.getStaticFolder(request, response);
folder = folder.replaceAll("\\\\", "/");
if(!(new File(folder+str).exists())){
new File(folder+str).mkdirs();
}
InputStream in = new FileInputStream(picturePath);
BufferedImage bi = ImageIO.read(in);
File file = new File(folder+str);
ImageIO.write(bi, "JPEG", file);
in.close();
}
String strBackUrl = "http://" + request.getServerName() //伺服器地址
+ ":"
+ request.getServerPort() //埠號
+ request.getContextPath(); //專案名稱
String folder = UserFileController.getImgFilesFolder(request, response);
newPicPath = content.replace(strBackUrl,folder);
information.setInfoText(newPicPath);
informationService.addInformation(information,user);
}
}
end!