Spring Boot+Thymeleaf+UEditor 图文上传

在APP中,介绍类文章都是图文混排形式展示。本文分享Spring Boot + Thymeleaf + UEditor图文上传。
第一步:下载并配置UEditor
 1、UEditor下载地址:http://ueditor.baidu.com/website/download.html    (选择对应的版本和开发语言下载)
 2、配置UEditor
    1)、解压下载文件,将目录jsp\src下的java源码拷贝到项目src目录下;
    2)、在pom.xml文件中配置ueditor对应的依赖包
            <dependency>  
                <groupId>org.json</groupId>  
                <artifactId>json</artifactId>  
            </dependency>  
            <dependency>  
                <groupId>commons-fileupload</groupId>  
                <artifactId>commons-fileupload</artifactId>  
                <version>1.3.2</version>  
            </dependency>  
            <dependency>  
                <groupId>commons-codec</groupId>  
                <artifactId>commons-codec</artifactId>  
                <version>1.9</version>  
            </dependency>
    3)、将解压缩文件下config.json文件拷贝到resources/static目录下;
    4)、将ueditor相应的包和js文件拷贝到resources/static目录下,如lang、themes、third-party、ueditor.all.js等;
    5)、修改配置文件(config.json)。修改字段"imageUrlPrefix : localhost:8081",该路径为访问路径;

    6)、修改配置文件(ueditor.config.js)。找到字段"serverUrl : localhost:8081/config",该路径用来读取配置文件。注:要与controller层中读取配置文件路径一致,下文会提到

第二步:实例化UEditor对象,并在页面展示
        1)、在resources/templates下创建目录ueditor目录测试UEditor,新建uploadImg.html文件。在文件中引入UEditor插件<script id="adtContent" name="adtContent" type="text/plain" style="width:100%;height:500px;"></script>
        2)、实例化插件,并配置基本信息:
            var ue = UE.getEditor('adtContent',{  
  toolbars:[['touppercase','tolowercase','forecolor','justifyleft','justifyright','justifycenter','justifyjustify','Undo',  'Redo','cleardoc','selectall','time','date','searchreplace','spechars','link','preview','simpleupload']],  

                //focus时自动清空初始化时的内容  
                autoClearinitialContent:true,  
                //关闭字数统计  
                wordCount:false,  
                //关闭elementPath  
                elementPathEnabled:false,  
                //默认的编辑区域高度  
                initialFrameHeight:400  
                //更多其他参数,请参考ueditor.config.js中的配置项  
            });
        3)、启动服务器,并访问http://localhost:8080/ueditor/uploadImg.html,如下图表示实例化成功
            Spring Boot+Thymeleaf+UEditor 图文上传
第三步:单个图片文件的上传
  1、读取配置信息(UEditorController.java),即上问提到的ueditor.config.js的读取,对应"serverUrl: 'http://localhost:8080/config'"。关键代码如下:
            @RequestMapping(value="/config")  
            public void config(HttpServletRequest request, HttpServletResponse response) {  
                response.setContentType("application/json");  
                String rootPath = request.getSession().getServletContext().getRealPath("/");          
                try {  
                    String exec = new ActionEnter(request, rootPath).exec();  
                    PrintWriter writer = response.getWriter();  
                    writer.write(exec);  
                    writer.flush();  
                    writer.close();  
                } catch (IOException e) {  
                           logger.error("读取配置文件失败,异常信息为:{0}" + e); 
                }  
            }
  2、服务端图片上传
        @RequestMapping(value = "/imgUpdate")
        @ResponseBody
        public String imgUpdate(MultipartFile upfile) throws FileNotFoundException {
  File path = new File(ResourceUtils.getURL("classpath:").getPath());
  String imgPath = path.getAbsolutePath() + "\\static\\img\\";
  if(!path.exists()) path = new File("");
           if (upfile.isEmpty()) {
               return "error";
           }     
           String fileName = upfile.getOriginalFilename(); // 获取文件名
           String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 获取文件的后缀名
           fileName = Calendar.getInstance().getTimeInMillis() + StrUtil.createRandom(true, 6) + suffixName;
           File dest = new File(imgPath + fileName);    
           if (!dest.getParentFile().exists()) { // 检测是否存在目录
               dest.getParentFile().mkdirs();
           }     
           try {
            upfile.transferTo(dest); // 上传图片     
            ObjectMapper mapper = new ObjectMapper();
            HashMap<String,Object> configs = new HashMap<String,Object>();    
            configs.put("state", "SUCCESS");
            configs.put("url", datdDirectory + newFileName);
            configs.put("title", newFileName);
            configs.put("original", newFileName);
   
            return mapper.writeValueAsString(configs);
           } catch (IllegalStateException e) {
            logger.error(e.toString());
           } catch (IOException e) {
            logger.error(e.toString());
           }
    
           return "error";
        }
  3、前端图片上传关键代码
                UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
                UE.Editor.prototype.getActionUrl = function(action) {
                    if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage') {
                        return 'http://localhost:8080/imgUpdate'; //在这里返回我们实际的上传图片地址
                    } else {
                        return this._bkGetActionUrl.call(this, action);
                    }
                }
            如图所示则表示成功

            Spring Boot+Thymeleaf+UEditor 图文上传