action:文件上传的接口
on-success:文件上传成功后的钩子函数,也就是给对应的字段初始化
FileController
核心功能
文件上传:通过/files/upload接口接收前端上传的文件
文件下载:通过/files/download/{fileName}接口提供文件下载
文件存储路径:
1
| private static final String filePath = System.getProperty("user.dir") + "/files/";
|
文件下载逻辑
1 2 3 4 5 6 7 8 9 10 11 12 13
| @GetMapping("/download/{fileName}") public void download(@PathVariable String fileName, HttpServletResponse response) { response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8)); byte[] bytes = FileUtil.readBytes(realFilePath); ServletOutputStream os = response.getOutputStream(); os.write(bytes); os.flush(); os.close(); }
|
使用@PathVariable获取文件名参数
设置Content-Disposition响应头告诉浏览器这是下载文件
使用URLEncoder对文件名编码,处理中文文件名问题
通过HttpServletResponse直接输出文件流
配置相关
1 2
| @Value("${fileBaseUrl}") private String fileBaseUrl;
|
从配置文件读取fileBaseUrl,灵活配置文件访问的基础URL
这样可以在不同环境(开发/测试/生产)使用不同的域名
前端
1 2 3 4 5 6 7
| <el-table-column label="头像" prop="avatar"> <template v-slot="scope"> <el-image :src="scope.row.avatar" style="width: 40px; height: 40px; border-radius: 50%"></el-image> </template> </el-table-column>
|
1 2 3 4 5 6 7 8
| <el-form-item label="头像" prop="avatar"> <el-upload :action="uploadUrl" list-type="picture" :on-success="handleImgSuccess"> <el-button type="primary">上传图片</el-button> </el-upload> </el-form-item>
|
1 2 3 4
|
const uploadUrl = import.meta.env.VITE_BASE_URL + '/files/upload';
|
1 2 3 4 5 6 7 8
|
const handleImgSuccess = (res) => { data.form.avatar = res.data.url }
|