Java maven项目集成ueditor(百度本编辑器)插件详解

来源:互联网 发布:宁波淘宝托管 编辑:程序博客网 时间:2024/05/18 21:06

相信很多项目都要用到类似的功能,ueditor是一个非常强大的插件,当然也有直接集成好的直接引用就行了。在这里讲一下百度编辑器的集成过程,本人是走了好多弯路,在这里希望各位开发的朋友少走些弯路,节约开发时间。

1,首先需要下载ueditor包  我下载的是  ueditor1_4_3_3-utf8-jsp ,然后引入项目里面  把相关的js和css  配置到配置文件中

2,第一步实现了 ,那么就要在jsp页面显示出来。很简单   

[html] view plain copy
  1. <div id="editor" style="width:794px;height:340px;"></div>  
  2. <script type="text/javascript">  
  3.     var ue = UE.getEditor('editor');  
  4. </script>  

3,难点在于图片的上传,以及各种配置

找到jsp文件夹里面config.json ,打开需要改两项 imageActionName  ,   imagePathFormat

[java] view plain copy
  1. /* 上传图片配置项 */  
  2.     "imageActionName""uploadImage"/* 执行上传图片的action名称 */  
  3.     "imageFieldName""upfile"/* 提交的图片表单名称 */  
  4.     "imageMaxSize"2048000/* 上传大小限制,单位B */  
  5.     "imageAllowFiles": [".png"".jpg"".jpeg"".gif"".bmp"], /* 上传图片格式显示 */  
  6.     "imageCompressEnable"true/* 是否压缩图片,默认是true */  
  7.     "imageCompressBorder"1600/* 图片压缩最长边限制 */  
  8.     "imageInsertAlign""none"/* 插入的图片浮动方式 */  
  9.     "imageUrlPrefix"""/* 图片访问路径前缀 */  
  10.     "imagePathFormat""/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}"/* 上传保存路径,可以自定义保存路径和文件名格式 */  
  11.                                 /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */  
  12.                                 /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */  
  13.                                 /* {time} 会替换成时间戳 */  
  14.                                 /* {yyyy} 会替换成四位年份 */  
  15.                                 /* {yy} 会替换成两位年份 */  
  16.                                 /* {mm} 会替换成两位月份 */  
  17.                                 /* {dd} 会替换成两位日期 */  
  18.                                 /* {hh} 会替换成两位小时 */  
  19.                                 /* {ii} 会替换成两位分钟 */  
  20.                                 /* {ss} 会替换成两位秒 */  
  21.                                 /* 非法字符 \ : * ? " < > | */  
  22.                                 /* 具请体看线上文档: fex.baidu.com/ueditor/#use-format_upload_filename */  
imageActionName -》执行上传图片的action名称

imagePathFormat-》上传保存路径,可以自定义保存路径和文件名格式

4,修改 ueditor.config.js  自定义编辑器的功能

[html] view plain copy
  1. /**  
  2.    * 编辑器资源文件根路径。它所表示的含义是:以编辑器实例化页面为当前路径,指向编辑器资源文件(即dialog等文件夹)的路径。  
  3.    * 鉴于很多同学在使用编辑器的时候出现的种种路径问题,此处强烈建议大家使用"相对于网站根目录的相对路径"进行配置。  
  4.    * "相对于网站根目录的相对路径"也就是以斜杠开头的形如"/myProject/ueditor/"这样的路径。  
  5.    * 如果站点中有多个不在同一层级的页面需要实例化编辑器,且引用了同一UEditor的时候,此处的URL可能不适用于每个页面的编辑器。  
  6.    * 因此,UEditor提供了针对不同页面的编辑器可单独配置的根路径,具体来说,在需要实例化编辑器的页面最顶部写上如下代码即可。当然,需要令此处的URL等于对应的配置。  
  7.    * window.UEDITOR_HOME_URL = "/xxxx/xxxx/";  
  8.    */  
  9.   var URL = window.UEDITOR_HOME_URL || getUEBasePath();  
  10.   /**  
  11.    * 配置项主体。注意,此处所有涉及到路径的配置别遗漏URL变量。  
  12.    */  
  13.   window.UEDITOR_CONFIG = {  
  14.   
  15.       //为编辑器实例添加一个路径,这个不能被注释  
  16.       UEDITOR_HOME_URL: URL  
  17.       // 服务器统一请求接口路径  
  18.       , serverUrl: URL + "jsp/controller.jsp"  
  19.       //工具栏上的所有的功能按钮和下拉框,可以在new编辑器的实例时选择自己需要的重新定义  
  20.       , toolbars: [[  
  21.           'bold', 'italic', 'underline', 'fontborder', 'strikethrough', '|', 'forecolor', 'backcolor', '|',  
  22.           'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',  
  23.           'fontfamily', 'fontsize', '|',  
  24.           'indent', '|',  
  25.           'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify',  
  26.           '|', 'inserttable',  
  27.           '|','simpleupload','imagenone', 'imageleft', 'imageright', 'imagecenter'  
  28.       ]]  
修改 toolbars

5,Java代码  上传图片 ,ueditor需要特定的返回值,title,original,size,state,type,url

controller里面定义名称和config.json里面imageActionName定义的一样,@RequestMapping("uploadImage")

[java] view plain copy
  1. @ResponseBody  
  2.     @RequestMapping("uploadImage")  
  3.     public Map<String,String> uploadImage(@RequestParam("upfile")  CommonsMultipartFile upfile,HttpServletRequest request,Model model) throws Exception{   
  4.           
  5.         //得到路径 C:/tomcat/webapps/testDemo/  
  6.         String rootPath = request.getSession().getServletContext().getRealPath("/");  
  7.         rootPath = rootPath.replaceAll("\\\\", "/");  
  8.           
  9.         String path = rootPath + "/ueditor/jsp/upload/image";  
  10.           
  11.         File f = new File(path);  
  12.         if (!f.exists()) {  
  13.             f.mkdirs();  
  14.         }  
  15.       
  16.         FileItem item = upfile.getFileItem();  
  17.         //文件路径  
  18.         String pathFileName = item.getName();  
  19.         //字节数  
  20.         long l = item.getSize();  
  21.         String fileSize = Long.toString(l);  
  22.         //文件名  
  23.         int start = pathFileName.lastIndexOf("\\");  
  24.         String fileName = pathFileName.substring(start + 1);  
  25.         //后缀 .jpg  
  26.         int indexName = fileName.lastIndexOf('.');  
  27.         String subName = fileName.substring(indexName);  
  28.         //新文件名  
  29.         String nowName = new SimpleDateFormat("yyMMddHHmmss").format(new Date()) +"_"+ fileName;  
  30.               
  31.         item.write(new File(path, nowName));  
  32.           
  33.         String strBackUrl = "http://" + request.getServerName() //服务器地址  
  34.         + ":"  
  35.         + request.getServerPort()           //端口号    
  36.         + request.getContextPath();      //项目名称  
  37.           
  38.         Map<String,String> map = new HashMap<String,String >();  
  39.         //文件原名称   
  40.         map.put("title", nowName);  
  41.         //现在文件名称  
  42.         map.put("original", fileName);  
  43.         //文件大小(字节数)  
  44.         map.put("size", fileSize);  
  45.         //是否上传成功  
  46.         map.put("state""SUCCESS");  
  47.         //文件类型 .+后缀名  
  48.         map.put("type", subName);  
  49.         //文件路径  
  50.         map.put("url",  strBackUrl+"/ueditor/jsp/upload/image/"+nowName);  
  51.           
  52.         return map;  
  53.           
  54.     }  

然后jsp里面需要调 uploadImage

[javascript] view plain copy
  1. UE.Editor.prototype._bkGetActionUrl ? "" : UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;  
  2.     UE.Editor.prototype.getActionUrl = function(action) {  
  3.         //这里很重要,很重要,很重要,要和配置中的imageActionName值一样  
  4.         if (action == 'uploadImage'){  
  5.             //这里调用后端我们写的图片上传接口  
  6.             return '${ctx}/sys/upload/uploadImage';  
  7.         }else{  
  8.             return this._bkGetActionUrl.call(this, action);  
  9.         <span style="white-space:pre">  </span>}  
  10.     }  

这样图片就在编辑器里面显示出来了


6,保存到数据库里是带有标签的text ,在这之前要把里面图片的路径替换成服务器的路径

[java] view plain copy
  1. private final static Pattern ATTR_PATTERN = Pattern.compile("<img[^<>]*?\\ssrc=['\"]?(.*?)['\"]?\\s.*?>",Pattern.CASE_INSENSITIVE);  
[java] view plain copy
  1. if (StringUtils.isEmpty(information.getId())) {  
  2.             information.setId(IdGenerator.uuid());  
[java] view plain copy
  1. <span style="white-space:pre">          </span>//得到ueditor内的内容  
  2.             String content = request.getParameter("editorValue");  
  3.               
  4.             Matcher matcher = ATTR_PATTERN.matcher(content);  
  5.             List<String> piclist = new ArrayList<String>();  
  6.             while (matcher.find()) {  
  7.                 piclist.add(matcher.group(1));  
  8.             }  
  9.               
  10.             if(piclist.size() == 0){  
  11.                 information.setInfoText(content);  
  12.                 informationService.addInformation(information,user);  
  13.             }else{  
  14.                 String newPicPath = "";  
  15.                 String str = "";  
  16.                 for (String string : piclist) {  
  17.                     //得到路径名/ueditor/jsp/upload/image/....  
  18.                     str = string.substring(string.indexOf("/ueditor"));  
  19.                     //得到存图片/ueditor/jsp/upload/image/....的项目路径  
  20.                     String rootPath = request.getSession().getServletContext().getRealPath("/");  
  21.                     rootPath = rootPath.replaceAll("\\\\", "/");  
  22.                     //本地图片的路径  
  23.                     String picturePath = rootPath+str;  
  24.                     String folder = UserFileController.getStaticFolder(request, response);  
  25.                     folder = folder.replaceAll("\\\\", "/");  
  26.                       
  27.                     if(!(new File(folder+str).exists())){  
  28.                         new File(folder+str).mkdirs();  
  29.                     }  
  30.                       
  31.                     InputStream in = new FileInputStream(picturePath);  
  32.                     BufferedImage bi = ImageIO.read(in);  
  33.                     File file = new File(folder+str);  
  34.                     ImageIO.write(bi, "JPEG", file);   
  35.                     in.close();  
  36.                 }  
  37.                   
  38.                 String strBackUrl = "http://" + request.getServerName() //服务器地址  
  39.                 + ":"  
  40.                 + request.getServerPort()           //端口号    
  41.                 + request.getContextPath();      //项目名称  
  42.                   
  43.                 String folder = UserFileController.getImgFilesFolder(request, response);  
  44.                 newPicPath = content.replace(strBackUrl,folder);  
  45.                 information.setInfoText(newPicPath);  
  46.                 informationService.addInformation(information,user);  
  47.             }  
  48.         }  
阅读全文
0 0