springboot整合ueditor

java1234

共 9321字,需浏览 19分钟

 · 2021-05-30

点击上方蓝色字体,选择“标星公众号”

优质文章,第一时间送达

  作者 |  dubuxiaoxiao

来源 |  urlify.cn/3ARrMf

也许并不是最简单的方法,仅记录自己成功的步骤

1.pom文件

ueditor用到了这三个依赖

<dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.4</version>
    </dependency>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20140107</version>
    </dependency>
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.9</version>
    </dependency>

2.下载ueditor

github下载了ueditor-1.4.3.3的压缩包,下载这个版本是因为有jsp文件,后面要用

3.前端配置

解压后放在项目可访问的路径,我直接放在了resources/static文件下,同时在static文件下添加test.html文件,内容如下

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>富文本部署测试</title>
    <script type="text/javascript" src="ueditor/ueditor.config.js"></script>
    <script type="text/javascript" src="ueditor/editor_api.js"></script>
</head>
<body>
<script id="container" name="content" type="text/plain">默认文本</script>
<script type="text/javascript">
    var ue = UE.getEditor('container')
</script>
</body>
</html>

其中有两个引入文件,ueditor.config.js本来就有,editor_api.js是从ueditor/_examples文件夹下复制来的(网上查到的是需要editor.all.js文件,需要执行命令生成,有人指出editor_api.js文件与editor.all.js相同,于是我直接用了editor_api.js文件),同时将editor_api.js文件中baseURL改为baseURL = 'ueditor/_src/'

随后添加test.html的controller,启动项目,访问test.html,看到富文本的编辑页面,表示这一步成功(失败大概是静态文件没找到,f12好好看下,确定有的话删除target,重新编译)

 

 

 

4.后端配置

上传下载功能不能用,f12查看,有localhost:8080/ueditor/php/controller.php?action=config&&noCache=1619763509006请求是失败的,这个请求是获取上传下载的一些配置信息的

解决:

(1)在ueditor.config.js中修改请求路径,serverUrl值改为fwbcontroller,同时controller文件中添加该请求路径与处理代码,如下:

@RequestMapping("/fwbcontroller")
@ResponseBody
public String uController(HttpServletRequest request) throws IOException, URISyntaxException {
    request.setCharacterEncoding( "utf-8" );
    return new ActionEnter( request, "" ).exec();
}

这是抄袭的ueditor/jsp/controller.jsp,因为后面修改了一些代码,new ActionEnter( request, "" )中的第二个参数就没有用了,直接写空字符串即可,同时复制引入ueditor/jso/src中的代码,ActionEnter的类描述就在这些代码里。

(2)改ueditor/jso/src文件的代码

引入还不行,代码有问题,要改,找到ConfigManager.java文件,readFile方法重写为:

private String readFile ( String path ) throws IOException {
   
   StringBuilder builder = new StringBuilder();
   
   try {
      ClassPathResource classPathResource = new ClassPathResource("static/ueditor/config.json");
      InputStream inputStream = classPathResource.getInputStream();
      InputStreamReader reader = new InputStreamReader( inputStream, "UTF-8" );
      BufferedReader bfReader = new BufferedReader( reader );
      
      String tmpContent = null;
      
      while ( ( tmpContent = bfReader.readLine() ) != null ) {
         builder.append( tmpContent );
      }
      
      bfReader.close();
      
   } catch ( UnsupportedEncodingException e ) {
      // 忽略
   }
   return this.filter( builder.toString() );
}

代码需要读取config.json文件,这个文件在ueditor/jsp中有,将其移动到ueditor/下(原先代码有缺陷,在将项目打包为jar之后config.json获取不到,不打包的话不会有影响)

之后是重头戏,网上很多人提这个问题,进入富文本后,上传图片,提示未找到数据,网上说这是ueditor和spring不兼容的原因,我最终debug到了ueditor的代码,发现BinaryUploader文件中的save方法存在问题(其中Iterator.hasNext()一开始就为false,按理说应该获取到request数据保存的,为什么没获取到呢...),修改save方法即可

try {
   MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
   MultipartFile multipartFile = multipartRequest.getFile(conf.get("fieldName").toString());

   String savePath = (String) conf.get("savePath");
   String originFileName = multipartFile.getOriginalFilename();
   String suffix = FileType.getSuffixByFilename(originFileName);

   originFileName = originFileName.substring(0,originFileName.length() - suffix.length());
   savePath = savePath + suffix;

   long maxSize = ((Long) conf.get("maxSize")).longValue();

   if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
      return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
   }
   /***********/
   //自定义
   savePath = PathFormat.parse(savePath, originFileName);

   String [] savePathBySplit_temp = savePath.split("/");
   String temp = "";
   String fileName = savePathBySplit_temp[savePathBySplit_temp.length-1];
   for(int i = 1;i < savePathBySplit_temp.length-1; i++){
      if(i!=savePathBySplit_temp.length-1){
         temp+=savePathBySplit_temp[i]+"/";
      }else{
         temp+=savePathBySplit_temp[i];
      }
   }
   String pathTemp = System.getProperty("java.io.tmpdir")+temp;
   System.out.println(pathTemp+","+fileName);
   System.out.println(new File(pathTemp).exists());
   File targetFile = new File(pathTemp);
   if(!targetFile.exists()){
      targetFile.mkdirs();
   }
   System.out.println(new File(pathTemp).exists());
   /************/
   //State storageState = StorageManager.saveFileByInputStream(multipartFile.getInputStream(),savePath, maxSize);
   State storageState = StorageManager.saveFileByInputStream(multipartFile.getInputStream(),pathTemp+"/"+fileName, maxSize);

   if (storageState.isSuccess()) {
      storageState.putInfo("url", PathFormat.format(savePath.substring(1)));
      storageState.putInfo("type", suffix);
      storageState.putInfo("original", originFileName + suffix);
   }

   return storageState;

}catch (Exception e) {
   e.printStackTrace();
   System.out.println(e.getMessage());
}
return new BaseState(false, AppInfo.IO_ERROR);

其中System.getProperty("java.io.tmpdir")获取到的是c:/users/用户名/Appdata/Local/Temp目录,将图片保存在这里(其他路径也可),同时在yml文件中添加这部分目录的映射,不然访问不到(红色是新添的,黑色是原先默认,都要写上)

spring:
  resources:
    static-locations: file:${java.io.tmpdir},classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

这下既可以保存到,又可以访问到了,重启项目,图片上传成功

另:config.json文件有上传文件的一些配置,如保存路径(指子路径,比如上面代码保存路径在Temp文件夹下,那么子路径从Temp开始,为"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}"

),图片大小限制等。

 

学习到的一些东西:

1.打包后的jar包无法使用普通的(普通指通过File或InputStream流等读取文件的方法)方法来获取其中的静态文件(因为jar包本身就只是一个文件),但可以使用类似如下方法:

ClassPathResource classPathResource = new ClassPathResource("static/ueditor/config.json");
InputStream inputStream = classPathResource.getInputStream();

从上面代码看出,默认目录好像是源代码中的resources目录,具体怎样还没有深入了解,另外网上也可以找到其他的一些方法,都可以在jar包中获取静态资源。

 






浏览 22
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报