Vue集成mavon-editor实现图片上传
项目环境:
前端:vue2
后端:springboot
前端
1. 安装mavon-editor
npm install mavon-editor@2.10.1
2. 在main.js引入
// ......
import Vue from 'vue'
import mavonEditor from "mavon-editor";
import "mavon-editor/dist/css/index.css"
// ......
Vue.use(mavonEditor)
3. 在vue页面中使用该组件
(1)@imgAdd
方法监听图片上传,可以获取到对应的图片文件。其中使用this.$refs
可以获得mavon-editor的实例(例如下面代码中<mavon-editor>
标签中ref
为md
,那么可以通过this.$refs.md
得到mavon-editor实例)
(2)@change
方法监听文本框中内容的变化,可以获取文本内容
<mavon-editor
v-model="content"
ref="md"
@imgAdd="imgAdd"
@change="change"
/>
// uploadImg为上传图片的接口
import { uploadImg } from "@/api/image";
export default {
data: function() {
return {
content: "",
html: "",
};
},
methods: {
imgAdd(pos, $file) {
// pos为位置,$file为图片文件
let formdata = new FormData();
formdata.append("image", $file);
// 按照格式传入对于的图片文件
uploadImg(formdata).then((res) => {
console.log(res)
// res.message为照片链接
// 请求后端接口后,将pos位置的图片路径替换为后端返回的图片链接
this.$refs.md.$img2Url(pos, res.message);
});
},
change(value, render) {
this.content = value
this.html = render;
},
}
};
前端具体代码可参考:https://gitee.com/chenxinyu_cxy/project-upload-img-frontend.git
后端
后端对应的实体类为Article
,对应的图片上传接口实现为:
@PostMapping("/upload")
public FileResult upload(@RequestParam("image") MultipartFile image) throws FileNotFoundException {
String path = ResourceUtils.getURL("classpath:").getPath()+"static/image";
File filePath = new File(path);
if (!filePath.exists() && !filePath.isDirectory()) {
filePath.mkdirs();
}
//获取原始文件名称(包含格式)
String originalFileName = image.getOriginalFilename();
assert originalFileName != null;
//获取文件后缀名
String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
//获取文件名(没有后缀)
String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));
String fileName = UUIDUtils.getUuid() + name + "." + type;
//在指定路径下创建一个文件
File targetFile = new File(path, fileName);
//将文件保存到服务器指定位置
try {
image.transferTo(targetFile);
//将文件在服务器的存储路径返回(此处为本地路径)
return new FileResult(true,"http://127.0.0.1:8080/image/"+fileName,path+"/"+fileName);
} catch (IOException e) {
return new FileResult(false, "上传失败","");
}
}
后端具体代码可参考:https://gitee.com/chenxinyu_cxy/project-file-upload-backend.git