最终效果
实现方法
这里只着重说明mavon-editor如何上传图片,其他更多配置可参考文档:mavon-editor文档。
<mavon-editor
ref="mdedit"
class="editBox"
:ishljs="true"
:codeStyle="code_style"
:externalLink="externalLink"
@imgAdd="imgAdd"
v-model="blogContent.content"
></mavon-editor>
上面代码中只需关注ref
属性和@imgAdd
事件,其他与上传图片功能无关。下面看一下imgAdd
事件的实现:
imgAdd(pos,file){
let imgData = new FormData();
imgData.append('file',file);
blogApi.uploadImage(imgData).then(res=>{
console.log(res.data.data);
console.log(this.$refs.mdedit)
this.$refs.mdedit.$img2Url(pos,res.data.data)
});
}
- pos: 写在md中的文件名
- file: 图片文件
然后通过form提交到服务端到上传接口,该接口会返回一个对应上传图片的链接,然后通过refs
拿到mavon-editor的实例,通过它的$img2Url
方法将md中文件名为pos的这个图片路径替换为服务端返回后的链接。
服务端接口
@PostMapping("/uploadImage")
public Rs uploadImage(MultipartFile file) throws IOException {
File saveFile = new File(uploadPath);
if(!saveFile.exists()) {
saveFile.mkdir();
}
String dateTime = TimeUtil.getDate();
String uuid = UUID.randomUUID().toString();
String saveName = dateTime+"-"+uuid+"-"+file.getOriginalFilename();
String savePathName = uploadPath+saveName;
File result = new File(savePathName);
file.transferTo(result);
String viewUrl = uploadUrl+saveName;
return RsUtil.success(viewUrl,"上传成功");
}
mavon-editor还有一个事件是imgDel
它是在删除图片文件后回调。可以根据自己的需求考虑是否实现该函数。