SpringBoot+Vue3实现文件上传功能
甲蛙全栈
共 1942字,需浏览 4分钟
·
2021-11-12 07:23
SpringBoot+Vue3实现文件上传功能,后端开发一个SpringBoot通用上传接口,前端使用Vue3的上传组件。
| 喜欢听我叨叨的,直接看视频 |
01
实现思路
1. 前端上传组件,html自带的file,Vue上传组件
https://2x.antdv.com/components/upload-cn#components-upload-demo-avatar
2. 后端接收,将图片保存到文件夹
SpringBoot通用的上传文件接口
3. 前端显示图片,将文件夹路径转为url
D:/file/wiki/xxx.jpg
D:/file/wiki/是文件目录
localhost:8880/file/xxx.jpg
02
相关代码
后端接口
@RequestMapping("/upload/avatar")
public CommonResp upload(@RequestParam MultipartFile avatar) throws IOException {
LOG.info("上传文件开始:{}", avatar);
LOG.info("文件名:{}", avatar.getOriginalFilename());
LOG.info("文件大小:{}", avatar.getSize());
// 保存文件到本地
String fileName = avatar.getOriginalFilename();
String fullPath = "D:/file/wiki/" + fileName;
File dest = new File(fullPath);
avatar.transferTo(dest);
LOG.info(dest.getAbsolutePath());
return new CommonResp();
}
HTML:
<a-upload
v-model:file-list="fileList"
name="avatar"
list-type="picture-card"
class="avatar-uploader"
:show-upload-list="false"
:action="SERVER + '/ebook/upload/avatar'"
:before-upload="beforeUpload"
@change="handleChange"
>
<img v-if="imageUrl" :src="imageUrl" alt="avatar" />
<div v-else>
<loading-outlined v-if="coverLoading">loading-outlined>
<plus-outlined v-else>plus-outlined>
<div class="ant-upload-text">Uploaddiv>
div>
a-upload>
JS:
function getBase64(img: Blob, callback: (base64Url: string) => void) {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result as string));
reader.readAsDataURL(img);
}
………………
const SERVER = process.env.VUE_APP_SERVER;
const fileList = ref([]);
const coverLoading = ref(false);
const imageUrl = ref('');
const handleChange = (info: any) => {
if (info.file.status === 'upcoverLoading') {
coverLoading.value = true;
return;
}
if (info.file.status === 'done') {
// Get this url from response in real world.
getBase64(info.file.originFileObj, (base64Url: string) => {
imageUrl.value = base64Url;
coverLoading.value = false;
});
ebook.value.cover = SERVER + "/file/" + info.file.name;
}
if (info.file.status === 'error') {
coverLoading.value = false;
message.error('upload error');
}
};
const beforeUpload = (file: any) => {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
message.error('You can only upload JPG file!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('Image must smaller than 2MB!');
}
return isJpgOrPng && isLt2M;
};
—————— THE END ——————
扫码关注,好文不错过
评论