一、环境介绍
wangEditor 3
springBoot 1.5.3.RELEASE
二、前端
- html
<script src="/thirdparty/wangEditor.min.js"></script>
<div id="editor">
<p>欢迎使用 <b>wangEditor</b> 富文本编辑器</p>
</div>
- js
var E = window.wangEditor;
var editor = new E('#editor');
editor.customConfig.uploadImgServer = '/articleImg/uploadImg';
editor.customConfig.uploadFileName = 'img';
editor.create();
三、后端
- Controller
@Controller
@RequestMapping("/articleImg")
public class ArticleImgController {
@Autowired
private ArticleImgService articleImgService;
@RequestMapping("/uploadImg")
@ResponseBody
public Map<String,Object> uploadImg(@RequestParam("img") List<MultipartFile> list){
Map<String,Object> map = new HashMap<String, Object>();
int errno = 1;
String[] data = new String[0];
try {
data = articleImgService.uploadImg(list);
errno = 0;
}catch (Exception e){
errno = 1;
e.printStackTrace();
}
map.put("errno",errno);
map.put("data",data);
return map;
}
}
- Service
public String[] uploadImg(List<MultipartFile> list) throws Exception {
String imgUploadAbsolutePath = ResourceUtils.getURL("classpath:").getPath() + "static";
log.info("imgUploadAbsolutePath: " + imgUploadAbsolutePath);
String imgUploadRelativePath = "/uplaod/articleimg/";
String finalPath = imgUploadAbsolutePath + imgUploadRelativePath;
File finalPathFile = new File(finalPath);
if(!finalPathFile.exists()){
finalPathFile.mkdirs();
}
log.info("finalPath: " + finalPath);
String[] urlData = new String[5];
int index = 0;
for(MultipartFile img : list) {
String fileName = img.getOriginalFilename();
if(fileName == "") {
continue;
}
String finalFileName = (new Date().getTime()) + Math.round(Math.random() * 1000)
+ fileName;
File newfile = new File( finalPath + finalFileName);
log.info("newfile path: " + newfile.getAbsolutePath());
img.transferTo(newfile);
ArticleImg articleImg = new ArticleImg();
articleImg.setImgName(finalFileName);
articleImg.setImgUrl(imgUploadRelativePath + finalFileName);
articleImg.setUploadTime(new Date());
insertSelective(articleImg);
urlData[index++] = imgUploadRelativePath + finalFileName;
log.info("urlData["+(index-1)+"]: " + urlData[index-1]);
}
return urlData;