# SpringMVC-Ueditor
**Repository Path**: devin-alan/springmvc-ueditor
## Basic Information
- **Project Name**: SpringMVC-Ueditor
- **Description**: Spring MVC整合UEditor
- **Primary Language**: Java
- **License**: Apache-2.0
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 3
- **Forks**: 2
- **Created**: 2017-05-16
- **Last Updated**: 2022-05-24
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
SpringMVC-Ueditor项目是一个Spring MVC与百度文本编辑器ueditor集成的例子(ps:部分代码来自网络),本例相比官方的jsp例子实现上更为优雅,并且将文件上传和下载的接口放在Controller中去实现更方便维护,包括ueditor的json配置文件的读取也是采用后台接口去实现。除此本例也是一个使用Ueditor去实现公告发布的简单例子,公告后台数据库初始sql在项目中,本例的目的不在于怎么实现公告发布、展示这些功能,主要目的提供一个好的集成方案和一些整合技术细节。
## 依赖管理
本例和百度ueditor整合所需jar均采用maven管理,下面是文件上传所需的依赖包,本例使用的com.baidu.ueditor的jar使用请参考https://git.oschina.net/songxinqiang/UeditorJavaLib
```
cn.songxinqiang
com.baidu.ueditor
1.1.2-edit-1.0
commons-fileupload
commons-fileupload
1.3.2
commons-io
commons-io
2.5
commons-codec
commons-codec
1.9
```
## 整合配置详解
1. 下载jsp版本的ueditor,只需将静态文件存放到项目中,里面的jsp和jar包都删除掉,因为这里面的文件不当便管理还占用空间,能够采用maven去管理jar包最好不过了(ps:课参考本项目ueditor的结构)
2. 将ueditor所需要的json文件放入resource下,并且最好重命名成ueditor.config.json方便识别(ps:请参考项目源码)
3. 编写controller去加载ueditor.config.json,这是直接参考com.baidu.ueditor使用即可,代码如下
```
**
* 获取百度editor编辑器配置文件
*
*/
@Controller
@RequestMapping("/ued")
public class UeditorController implements ServletContextAware {
private String rootPath;
/**
* 获取resource文件下的editor配置文件ueditor.config.json
* @param request
* @return
*/
@RequestMapping("/ueditor")
@ResponseBody
public String ueditorConfig(HttpServletRequest request) {
return new ActionEnter(request, rootPath, UeditorController.class.getClassLoader()
.getResource("ueditor.config.json").getPath()).exec();
}
@Override
public void setServletContext(ServletContext servletContext) {
rootPath = servletContext.getRealPath("/");
}
}
```
4.修改ueditor静态文件ueditor.config.js中的serverUrl的值为第3中编写api路径,真实项目不推荐将服务器根路径写死在js中,应该获取root path再加上我们获取配置文件api
```
serverUrl: "http://localhost:8080/ued/ueditor"
```
5.页面集成ueditor只需导入css和下面的几个js文件即可,具体请参考项目下ueditorDemo.jsp
```
```
6.编写文件上传和下载的接口官方例子是通过controller.jsp去上传文件,现在在jsp中硬编码后台逻辑并不好,所以还是自己实现上传接口,详细代码请看项目源码
```
@Controller
@RequestMapping("attach")
@PropertySource("classpath:upload.properties")
public class UploadController {
private Logger LOGGER = LoggerFactory.getLogger(UploadController.class);
@Resource
Environment env;
/**
* 注意RequestParam的value必须和ueditor.config.json中imageFieldName的值相同
*
* @param file
* @return
*/
@ResponseBody
@RequestMapping(value = "/uploadFile")
public Map uploadFile(@RequestParam(value = "upfile", required = false) MultipartFile file, HttpServletRequest request) {
Attachment attach = new Attachment();
//获取文件保存后面的动态路径
String backPath = this.getPath();
//服务器地址
StringBuilder serverPath = new StringBuilder();
serverPath.append("http://");
serverPath.append(request.getServerName()).append(":").append(request.getServerPort());
serverPath.append(request.getContextPath());
//文件保存的完整路径
String path = env.getProperty("fileBaseStoreDIR") + "/" + backPath;
//获取文件名
String fileName = file.getOriginalFilename();
//获取转换后的uuid文件名
String uuidFileName = this.getUUIDFileName(fileName);
//完善附件对象信息,如果需要设置
attach.setCreateTime(System.currentTimeMillis());
attach.setSize(file.getSize());
attach.setName(uuidFileName);
attach.setExt(this.getExtName(fileName, '.'));
attach.setRealPath(backPath + "/" + uuidFileName);
File targetFile = new File(path, uuidFileName);
//创建文件夹
if (!targetFile.exists()) {
targetFile.mkdirs();
}
Map map = new HashMap<>();
try {
//分装百度上传信息
file.transferTo(targetFile);
map.put("state", "SUCCESS");
map.put("url", serverPath+env.getProperty("downloadApi")+ uuidFileName);
map.put("title", "");
map.put("original", fileName);
} catch (Exception e) {
LOGGER.error("upload error:", e);
map.put("state", "上传失败");
}
return map;
}
/**
* download:附件下载.
*
* @param response
* @param name 唯一的文件名
* @throws IOException
*/
@RequestMapping("/download")
public void download(HttpServletResponse response, String name) throws IOException {
if (StringUtils.hasText(name)) {
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes("utf-8"), "iso-8859-1")); //转码之后下载的文件名不会出现中文乱码
response.setContentType("application/octet-stream;charset=UTF-8");
String backPath = this.getPath();
//文件保存的完整路径
String path = env.getProperty("fileBaseStoreDIR") + "/" + backPath + "/" + name;
//读取文件
InputStream in = new FileInputStream(path);
OutputStream out = response.getOutputStream();
//写文件
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
in.close();
out.close();
}
}
}
```
7.在集成页面中添加下列代码来调用自己的文件上传接口,详情请参考ueditorDemo.jsp
```
////请求自己的接口上传文件
UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
UE.Editor.prototype.getActionUrl = function (action) {
if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadvideo') {
return '${ctx}/attach/uploadFile';
} else {
return this._bkGetActionUrl.call(this, action);
}
};
```
8.发布内容回显到编辑器,这个一定要在ue编辑器ready完后在去设置回显内容,细节请阅读官方文档,参考下列代码
```
var ue = UE.getEditor('myEditor');
//对编辑器的操作最好在编辑器ready之后再做,否则会导致一些问题
ue.ready(function() {
//设置编辑器的内容
ue.setContent('${content}');
});
```
9.前端展示使用ueditor发布内容的注意事项,在展示的时候需要对展示内容的p标签设置换行,否则会出现显示不友好,参考样式如下
```
.article-text p{
word-break:break-all
}
```
## 优点总结
1. 文件存储路径可以配置为脱离项目之外的磁盘文件
2. 上传下载接口可自由控制和维护
## 优化建议
1. 实际项目中需要将相关的文件上传路径写入配置文件,不能像demo一样写在常量类中