前端:
$summernote = $("#summernote");
$summernote.summernote({
height: 500,
lang: 'zh-CN',
onImageUpload: function(files, editor, $editable) {
sendFile(files[0], editor, $editable);
}
});
function sendFile(file, editor, welEditable) {
data = new FormData();
data.append("file", file);
data.append("name", file.name);
$.ajax({
data: data,
type: "POST",
url: "${pageContext.request.contextPath}/api/image/upload",
cache: false,
contentType: false,
processData: false,
success: function(data) {
var MsgBox = $("body");
if (data.code == '200') {
$summernote.summernote('editor.insertImage', data.data);
MsgBox.message({
type: 'success',
content: '上传成功。'
});
} else {
MsgBox.message({
type: 'error',
content: '上传失败。'
});
}
}
});
}
后端:
@RequestMapping(value = "/image/upload", method = RequestMethod.POST)
@ResponseBody
public ResultMessage<String> uploadFileHandler(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file, HttpServletRequest request) {
ResultMessage<String> message = new ResultMessage<>();
if (!file.isEmpty()) {
try {
String rootPath = SpringContextHolder.getServletContext().getRealPath("/");
File dir = new File(rootPath + File.separator + "upload" + File.separator
+ DateJdk8Utils.formatDate(LocalDateTime.now(), "yyyyMMdd"));
if (!dir.exists())
dir.mkdirs();
File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
FileUtils.copyInputStreamToFile(file.getInputStream(), serverFile);
String fileUrl = QiNiuUitls.uploadImage(serverFile);
message.setData(fileUrl);
message.setCode(GlobalConstants.RESULT_SUCCESS);
serverFile.delete();
} catch (Exception e) {
message.setCode(GlobalConstants.RESULT_FAIL);
message.setMsg("You failed to upload " + name + " => " + e.getMessage());
}
} else {
message.setCode(GlobalConstants.RESULT_FAIL);
message.setMsg("You failed to upload " + name + " because the file was empty.");
}
return message;
}