一、文件上传
文件上传是将用户放入在博文中的图片上传到服务器中。
1.前端
在mavon-editor中绑定imgAdd,imgDel事件。
<div id="editor" v-on:mousedown="onWrite" v-on:mouseleave="onRead">
<mavon-editor ref=md :ishljs="true" @imgAdd="imgAdd" @imgDel="imgDel" v-model="content" v-bind:style="styleChange" ></mavon-editor>
</div>
// 绑定@imgAdd event
imgAdd(pos, $file) {
// 第一步.将图片上传到服务器.
this.img_file[pos] = $file;
let formdata = new FormData();
formdata.append('image', $file);
fetch("/api/blog/uploadImg",{
method: 'post',
body: formdata
}).then(result => {
if (!result.ok) {
alert("通信失败,请联系管理员!");
}
return result.json()
}).then((res) => {
if(res.result === true){
// 第二步.将返回的url替换到文本原位置 -> 
this.$refs.md.$img2Url(pos, res.url);
}
})
},
imgDel(pos) {
delete this.img_file[pos];
},
前端将后台返回的文件url地址替换文本原来的位置。就可以回显了。
2.后端
后端保存文件到磁盘,并且返回改地址的url
/**
* 文件上传
* @param image image
* @return Map<String, Object>
*/
@RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> uploadFile(MultipartFile image) {
Map<String, Object> map = new HashMap<>(2);
//本地使用,上传位置
String rootPath = null;
if(System.getProperty("os.name").startsWith("Windows")) {
rootPath = "D:\\Users\\Documents\\uploads\\";
}else if (System.getProperty("os.name").startsWith("Linux")){
rootPath = "/usr/local/upLoads/";
}
//文件的完整名称,如spring.jpeg
String filename = image.getOriginalFilename();
//文件后缀,如.jpeg
String suffix = filename.substring(filename.lastIndexOf("."));
//创建年月文件夹
Calendar date = Calendar.getInstance();
File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH) + 1));
//目标文件
File descFile = new File(rootPath + File.separator + dateDirs + File.separator + filename);
String newFilename = UUID.randomUUID() + suffix;
String parentPath = descFile.getParent();
descFile = new File(parentPath + File.separator + newFilename);
//判断目标文件所在的目录是否存在
if (!descFile.getParentFile().exists()) {
//如果目标文件所在的目录不存在,则创建父目录
descFile.getParentFile().mkdirs();
}
//将内存中的数据写入磁盘
try {
image.transferTo(descFile);
} catch (Exception e) {
e.printStackTrace();
log.error("上传失败,cause:{}", e);
map.put("result", false);
return map;
}
//完整的url
String fileUrl = "http://www.sustly.xyz:8081/blog/getImg?url=" + descFile;
log.info(fileUrl);
map.put("result", true);
map.put("url", fileUrl);
return map;
}
注意:
String fileUrl = "http://www.sustly.xyz:8081/blog/getImg?url=" + descFile;
这一句非常重要,getImg是回显的请求url则是请求的参数。
二、回显
前端只需要一些样式即可
<div id="content" v-highlight v-html="blog.content" class="markdown-body"></div>
因为前端的img标签的src中就是我们上面完整的url,我们只需将这个get请求返回一个图片文件即可。
@RequestMapping(value = "/getImg", method = RequestMethod.GET)
public void getFile(@RequestParam("url")String url,
HttpServletResponse response) throws IOException {
File file = new File(url);
log.info(url);
ServletOutputStream outputStream = response.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[1024];
while (fileInputStream.read(bytes) != -1){
outputStream.write(bytes);
}
outputStream.flush();
fileInputStream.close();
outputStream.close();
}