本文介绍UEditor图片上传功能的实现。
使用的例子项目架构如下:
freemaker + spring boot + spring mvc + maven
例子项目已上传码云,码云地址如下:
http://git.oschina.net/imlichao/ueditor-example-image_upload
前端部署
下载UEditor项目包,并部署到项目中
pring boot项目放在静态资源目录下
在页面加载UEditor
<!DOCTYPE HTML>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8">
<title>ueditor demo</title>
<!-- spring boot默认静态资源跟目录在static下 -->
<script type="text/javascript" charset="utf-8" src="/ueditor1_4_3_3/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="/ueditor1_4_3_3/ueditor.all.min.js"></script>
<script type="text/javascript" charset="utf-8" src="/ueditor1_4_3_3/lang/zh-cn/zh-cn.js"></script>
</head>
<body text-align:center>
<table style="margin:0 auto;">
<tr><td><h1>ueditor demo</h1></td></tr>
<tr><td><script id="editor" type="text/plain" style="width:1024px;height:500px;"></script></td></tr>
</table>
<script type="text/javascript">
var ue = UE.getEditor('editor');
</script>
</body>
</html>
执行效果
到这里UEditor一些基础的编辑功能已经能够使用了,但是像图片上传这一类功能还需要进行后台配置。
后端部署
目录结构
配置后台统一请求路径
在ueditor.config.js找到serverUrl参数修改为自己的后台请求接收方法
// 服务器统一请求接口路径 , serverUrl: "/ueditor/interface"
编写请求接收方法
/**
* ueditor 服务器统一请求接口(GET)
* @param action config 加载时获取配置文件
* @return
*/
@RequestMapping(value = "/ueditor/interface", method = RequestMethod.GET)
@ResponseBody
public String ueGetInterface(String action) {
System.out.println("Successful GET interface call");
return null;
}
测试请求路径是否设置成功。
ue在加载时会调用一次serverUrl,我们可以在接收方法内打断点或打印日志进行测试。
在这里要对统一请求路径做一下说明:
ueditor会将所有的后台请求发送至统一请求路径。
不同的功能会使用不同的方式提交,获取配置使用GET提交,上传图片或文件使用POST提交,所以接口要分开两个方法写。
既然所有的后台请求都发送到一个接口,那么怎么区分请求的是什么功能呢?答案就是action参数,action传入“config”时代表获取配置,action传入“uploadimage”时代表上传图片,还有其他的值在这里就不做一一列举了,可以自己去看api文档。
设置上传配置
在服务器统一请求接口中获取配置并转换成json形式返回
/**
* ueditor 服务器统一请求接口(GET)
* @param action config 加载时获取配置文件
* @return
*/
@RequestMapping(value = "/ueditor/interface", method = RequestMethod.GET)
@ResponseBody
public String ueGetInterface(String action) {
System.out.println("Successful GET interface call");
//创建文件上传配置文件类并转换为json方式返回
if(action != null && action.equals("config")){
try {
ObjectMapper mapper = new ObjectMapper();
String config = mapper.writeValueAsString(new UeditorUploadConfig());
return config;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
package pub.lichao.ueditor.controller;
/**
* Ueditor 文件上传配置
*/
public class UeditorUploadConfig {
/**
* 执行上传图片的action名称
*/
private String imageActionName="uploadimage";
/**
* 提交的图片表单名称
*/
private String imageFieldName="upfile";
/**
* 上传大小限制,单位B
*/
private Integer imageMaxSize=2048000;
/**
* 上传图片格式显示
*/
private String[] imageAllowFiles=new String[]{".png",".jpg",".jpeg",".gif"};
/**
* 是否压缩图片
*/
private Boolean imageCompressEnable=true;
/**
* 图片压缩最长边限制
*/
private Integer imageCompressBorder=1600;
/**
* 插入的图片浮动方式
*/
private String imageInsertAlign="none";
/**
* 图片访问路径前缀
*/
private String imageUrlPrefix="";
... get set 方法 ...
}
编写图片上传逻辑
本项目将图片保存到了项目本地路径中,在实际应用中往往会将图片保存在专门的图片服务器中。例如阿里云的OSS
/**
* ueditor 服务器统一请求接口(POST)
* @param action uploadimage 图片上传
* @return
*/
@RequestMapping(value = "/ueditor/interface", method = RequestMethod.POST)
@ResponseBody
public String uePostInterface(String action,MultipartFile upfile, HttpServletRequest request) {
System.out.println("Successful POST interface call");
//转换json格式工具
ObjectMapper mapper = new ObjectMapper();
//返回值对象
ImageState imageState = new ImageState();
try {
//执行图片上传并返回json格式结果
if(action != null && action.equals("uploadimage")){
System.out.println("uploadimage");
//保存文件(将图片上传到项目中,生产应用中会使用OSS等文件服务器进行存放)
String dirPath = request.getSession().getServletContext().getRealPath("/images");
new File(dirPath).mkdirs(); //创建目录
System.out.println("图片保存在{"+dirPath+"}目录中");
//为防止重名使用时间戳重新命名
String filename = "image" + Long.toString(System.currentTimeMillis()) + "." + FilenameUtils.getExtension(upfile.getOriginalFilename()); ;
String filePath = dirPath + "/" + filename;
upfile.transferTo(new File(filePath));//转存文件
//组装返回值
imageState.setState("SUCCESS");
imageState.setOriginal(upfile.getOriginalFilename());
imageState.setSize(Long.toString(upfile.getSize()));
imageState.setTitle(filename);
imageState.setType(upfile.getContentType());
String url = request.getScheme() +"://" + request.getServerName() + ":" +request.getServerPort() + request.getContextPath() + "/images/" + filename;
imageState.setUrl(url);
return mapper.writeValueAsString(imageState);
}else{
imageState.setState("无匹配的action类型");
return mapper.writeValueAsString(imageState);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
package pub.lichao.ueditor.controller;
/**
* Ueditor 图片返回值
*/
public class ImageState {
/**
* 上传状态 上传成功时必须返回"SUCCESS",失败时可以返回错误提示
*/
private String state;
/**
* 上传的原文件名
*/
private String original;
/**
* 文件大小
*/
private String size;
/**
* 上传后的新文件名
*/
private String title;
/**
* 文件类型
*/
private String type;
/**
* 图片访问地址
*/
private String url;
... get set 方法 ...
}
访问图片
图片上传成功后要给前台返回一个图片的访问地址,图片才能够正常在插件中展示。这里提供有一个访问项目中图片的类用于本例子使用。如果是使用文件服务器就不用此部分代码了,直接使用服务器提供的url返回给前台展示即可。
package pub.lichao.ueditor.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.nio.file.Paths;
@Controller
public class ImageController {
private final ResourceLoader resourceLoader;
@Autowired
public ImageController(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
/**
* 访问图片
* @param imagename
* @param request
* @return
*/
@RequestMapping(value = "/images/{imagename:.+}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> images(@PathVariable String imagename,HttpServletRequest request) {
try {
String dirPath = request.getSession().getServletContext().getRealPath("/images");
return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(dirPath, imagename).toString()));
} catch (Exception e) {
return ResponseEntity.notFound().build();
}
}
}
其实图片上传是一个比较容易实现的功能,此文希望对大家有帮助。