Springboot3+vue3实现文件上传和下载
文件下载
/**
* 文件下载
* 下载路径:"http://localhost:9999/files/download/logo.jpg"
*/
@GetMapping("/download/{fileName}")
public void download(@PathVariable String fileName, HttpServletResponse response) throws Exception {
//找到文件的位置
String filePath = System.getProperty("user.dir") + "/files/";//获取到当前项目的根路径(code的绝对路径 C:\Users\lenovo\Desktop\毕设\代码\code
String realPath = filePath + fileName;//C:\Users\lenovo\Desktop\毕设\代码\code\files\logo.jpg
boolean exist = FileUtil.exist(realPath);
if (!exist) {
throw new CustomerException("文件不存在");
}
//读取文件的字节流
byte[] bytes = FileUtil.readBytes(realPath);
ServletOutputStream os = response.getOutputStream();
//输出流对象把文件写出到客户端
os.write(bytes);
os.flush();
os.close();
}
文件上传
/**
* 文件上传
*/
@PostMapping("/upload")
public Result upload(@RequestParam("file") MultipartFile file) throws Exception {
//找到文件的位置
String filePath = System.getProperty("user.dir") + "/files/";
if (!FileUtil.isDirectory(filePath)) {
FileUtil.mkdir(filePath);
}
byte[] bytes = file.getBytes();
String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();//文件的原始名称
//写入文件
FileUtil.writeBytes(bytes,filePath + fileName);
String url = "http://localhost:9999/files/download" + fileName;
return Result.success(url);
}
在数据库表 admin 和 user 里面加上 avatar 字段

注意在 Mapper.xml 里面加上 avatar 的sql

前端对接文件上传和下载
文件上传到数据库存储的是一串 url 链接的字符串

表单上传
<el-form-item prop="avatar" label="头像">
<el-upload
action = "http://localhost:9999/files/upload"
:headers="{ token:data.user.token}"
:on-success="handleFileSuccess"
list-type="picture">
<el-button type="primary">上传头像</el-button>
</el-upload>
</el-form-item>
const handleFileSuccess = (res) => {
data.form.avatar = res.data
}
表格显示图片
<el-table-column label="头像">
<template #default="scope">
<el-image v-if="scope.row.avatar" :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]" :preview-teleported="true"
style="width: 40px;height: 40px;border-radius: 50%;display:block"/>
</template>
图片预览效果不理想,加上属性:preview-teleported="true"


浙公网安备 33010602011771号