项目场景:
springBoot框架下实现
问题描述:
Editormd文本框的图片上传
成功界面:
前端代码
<div class="form-group" id="blog-editormd">
<textarea style="display:none;" th:utext="${blog!=null and blog.blogContent!=null}?${blog.blogContent}: ''"></textarea>
</div>
js代码(部分,重点时写后端)
blogEditor = editormd("blog-editormd", {
width: "100%",
height: 640,
syncScrolling: "single",
path: "/admin/plugins/editormd/lib/", //插件保存的位置
toolbarModes: 'full',
/**图片上传配置*/
imageUpload: true,//开启图片上传功能
imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"], //图片上传格式
imageUploadURL: "/admin/blogs/md/uploadfile",//选好图片之后,上传时的后端(java层)地址
onload: function (obj) { //富文本框加载时的回调
}
});
java代码(功能实现)
@ApiOperation(value = "富文本框 图片本地上传")
@PostMapping("/blogs/md/uploadfile")
@ResponseBody
public Map uploadfile(@RequestParam(value = "editormd-image-file", required = false) MultipartFile file,
HttpServletRequest request,
HttpServletResponse response) {```
Map map = new HashMap();
try {
//设置
request.setCharacterEncoding("utf-8");
response.setHeader("Content-Type", "text/html");
//这个地址拿到的是项目根路径所在的地址。
String pathRoot1 = Blog.class.getResource("/").getPath().replaceAll("^(/)|(/WEB-INF/classes/)$", "");
//存放图片的地址(target文件夹下)
String rootPath =pathRoot1+"static/img/blog/";
// System.out.println("editormd上传图片:"+rootPath);//图片将要上传的位置
/**
* 文件路径不存在则需要创建文件路径
* */
File filePath = new File(rootPath);
if (!filePath.exists()) {
filePath.mkdirs();
}
// 最终文件
File realFile = new File(rootPath + File.separator + file.getOriginalFilename());
// 保存文件
FileUtils.copyInputStreamToFile(file.getInputStream(), realFile);
// 下面返回的json格式是editor.md所限制的,规范输出就OK,我用的map组装了一下
map.put("success", 1);
map.put("message", "上传成功");
String url = "/img/blog/"+file.getOriginalFilename();
map.put("url", url);//这个url会被页面拼接,
} catch (Exception e) {
map.put("success", 0);
map.put("message", "上传失败");
map.put("url", "");
e.printStackTrace();
}
return map;
}
总结:
1.文件的存储位置:我项目中放在target/static/img/blog/下,问题是:页面可以直接访问静态资源。优化方向是可以将文件存储在被定义的拦截器拦截的文件夹下但这样会导致图片的回显出问题。
地址的获取使用了一个大佬博客上的方法:
ClassName.class.getResource("/").getPath().replaceAll("^(/)|(/WEB-INF/classes/)$", “”);
ClassName为类名,我用的项目中的一个Blog类.
2.回传的url的组装(看代码)
3.返回值的组装,固定格式。前端要求返回的类型必须是json格式。在方法上添加注解@ResponseBody可以解决了。