本文旨在整合百度前端富文本Ueditor与SpringMVC,使用Spring Controller作为Ueditor的后端,提供上传图片等后台相关的功能,即使用SpringMVC替换官方提供的JSP后台方式。
创建web工程,本文以maven进行创建和管理,最终目录结构如下:
创建Ueditor统一后台Controller服务
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("/ued")
public class UeditorController{
@RequestMapping("/serverUrl")
@ResponseBody
public Object test(HttpServletRequest request,
@RequestParam(value = "action") String action,
@RequestParam(value = "upfile", required = false) MultipartFile file) throws Exception {
switch (action) {
case "config": // 加载返回ueditor配置文件conf/config.json
return getConfig();
case "uploadimage": // 上传图片
return uploadImage(request, file);
case "uploadvideo": // 上传视频
return "视频处理方法";
case "uploadfile": // 上传文件
return "文件处理方法";
default:
return "无效action";
}
}
private String getConfig() throws Exception {
File file = ResourceUtils.getFile("classpath:conf/config.json");
String json = FileUtils.readFileToString(file, "utf-8");
return json;
}
private Map uploadImage(HttpServletRequest request, MultipartFile file) {
String state = "SUCCESS";
String savedDir = request.getSession().getServletContext().getRealPath("upload");
String filename = file.getOriginalFilename();
File filepath = new File(savedDir,filename);
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
// 写到服务器路径下,可扩展,比如上传到云端或文件服务器
file.transferTo(new File(savedDir + File.separator + filename));
String uploadHttpUrl = "http://localhost:8083/upload"+ File.separator + filename;
return resultMap(file, state, uploadHttpUrl);
}
private Map resultMap(MultipartFile file, String state, String uploadHttpUrl) {
Map resMap = new HashMap();
resMap.put("state", state); //"SUCCESS" 表示成功
resMap.put("title", file.getOriginalFilename());
resMap.put("original", file.getOriginalFilename());
resMap.put("type", file.getContentType());
resMap.put("size", file.getSize());
resMap.put("url", uploadHttpUrl);
return resMap;
}
}
配置ueditor.config.js
把文件中的serverUrl: URL + "jsp/controller.jsp",修改为serverUrl: "/ued/serverUrl" 即可。
下章主要介绍如何优化ueditor和修改目前存在的bug