参考网址:https://www.freesion.com/article/6840704057/
1.前言
最近正在使用vue和springboot开发一个项目,其中做了一个使用markdown编辑器写文章的功能。在里面会用到图片上传,刚开始图片总是显示不出来,不过通过查看各种资料,总算把它做出来了。下面我就来讲一下我是怎么做出来的。
2.思路
图片上传的大概思路如下:
- 前端选择图片
- 将图片上传到服务器
- 将图片保存到服务器
- 服务器返回给前端图片地址链接
- 前端回显图片
3.开发步骤
3.1安装MAVON-EDITOR
npm install mavon-editor --save
3.2引入及配置
import {mavonEditor} from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
3.3使用MAVONEDITOR
<template>
<div>
<mavon-editor
v-model="content"
ref="md"
@change="change"
@imgAdd="imgAdd"
/>
<button @click="submit">提交</button>
</div>
</template>
<script>
import {mavonEditor} from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import {upload} from '@/network/upload'
export default {
name: 'MarkdownEditor',
// 注册
components: {
mavonEditor,
},
data() {
return {
content: '',
html: '',
configs: {}
}
},
methods: {
// 将图片上传到服务器,返回地址替换到md中
imgAdd(pos, $file) {
let formdata = new FormData();
formdata.append('image', $file);
//访问后台服务器方法
upload(formdata).then(res => {
if (res.code === 200) {
this.$refs.md.$img2Url(pos, res.data[0].url);
} else {
this.$message.error(res.message)
}
}).catch(err => {
console.log(err)
})
},
change(value, render) {
this.html = render;
},
// 提交
submit() {
console.log(this.content);
console.log(this.html);
}
},
mounted() {
}
}
</script>
3.4后台图片上传功能
3.4.1配置
在application.properties中配置文件保存的基本路径
upload.path =/files/
3.4.2控制层代码
@Value("${upload.path}")
private String baseFolderPath;
@PostMapping("/upload")
public ApiResponse upload(HttpServletRequest request, MultipartFile image) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String filePath = sdf.format(new Date());
File baseFolder = new File(baseFolderPath + filePath);
if (!baseFolder.exists()) {
baseFolder.mkdirs();
}
StringBuffer url = new StringBuffer();
url.append(request.getScheme())
.append("://")
.append(request.getServerName())
.append(":")
.append(request.getServerPort())
.append(request.getContextPath())
.append(baseFolderPath)
.append(filePath);
String imgName = UUID.randomUUID().toString().replace("_", "")
+ "_" + image.getOriginalFilename().replaceAll(" ", "");
try {
File dest = new File(baseFolder, imgName);
FileCopyUtils.copy(image.getBytes(), dest);
url.append("/").append(imgName);
JSONObject object = new JSONObject();
object.put("url", url);
return ApiResponse.buildSuccessResponse(object);
} catch (IOException e) {
log.error("文件上传错误 , uri: {} , caused by: ", request.getRequestURI(), e);
return ApiResponse.buildErrorMessage("文件上传错误");
}
}
3.4.3配置文件磁盘图片URL 映射
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**").addResourceLocations("file:/files/");
}
}
4.效果
5.总结
至此,图片上传功能就已经开发完成了,可能还有很多不足,欢迎大家给予意见和建议。
|