文件上传、下载
/**
* 文件相关操作接口
*/
@RestController
@RequestMapping("/files")
public class FileController {
// 表示本地磁盘文件的存储路径
private static final String filePath = System.getProperty("user.dir") + "/files/";
@Value("${fileBaseUrl}")
private String fileBaseUrl;
@Resource
private StudentMapper studentMapper;
@Resource
private ApprovalService approvalService;
/**
* 文件上传
*/
@PostMapping("/upload")
public Result upload(MultipartFile file) {
// 定义文件的唯一标识
String fileName = System.currentTimeMillis() + "-" + file.getOriginalFilename();
// 拼接完整的文件存储路径
String realFilePath = filePath + fileName;
try {
if (!FileUtil.isDirectory(filePath)) {
FileUtil.mkdir(filePath);
}
FileUtil.writeBytes(file.getBytes(), realFilePath);
} catch (IOException e) {
System.out.println("文件上传错误");
}
String url = fileBaseUrl + "/files/download/" + fileName;
return Result.success(url);
}
/**
* 文件下载
*/
@GetMapping("/download/{fileName}")
public void download(@PathVariable String fileName, HttpServletResponse response) {
// 设置下载文件http响应头
try {
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
// 拼接完整的文件存储路径
String realFilePath = filePath + fileName;
try {
// 通过文件的存储路径拿到文件字节数组
byte[] bytes = FileUtil.readBytes(realFilePath);
ServletOutputStream os = response.getOutputStream();
// 将文件字节数组写出到文件流
os.write(bytes);
os.flush();
os.close();
} catch (IOException e) {
System.out.println("文件下载错误");
}
}
/**
* 文件下载的url
*/
@GetMapping("/downloads")
public Result downloadStudent(@RequestParam String code, HttpServletResponse response) {
Student student = studentMapper.selectByCode(code);
return Result.success(student.getResume());
}
}
文件上传实现字段
<el-form-item label="简历" prop="resume">
<el-upload :action="uploadUrl" list-type="text" :on-success="handleImgSuccess_job" :file-list="data.fileList_job" :limit="1">
<el-button type="primary">上传简历</el-button><span style="color: red;">更换简历前请先将原简历删除,在选择新简历</span>
</el-upload>
</el-form-item>
:action是文件上传是触发的函数 。
// 文件上传的接口地址
const uploadUrl = import.meta.env.VITE_BASE_URL + '/files/upload'
:on-success是处理文件上传成功后的钩子函数
const handleImgSuccess_job = (res) => {
data.form.resume = res.data // res.data就是文件上传返回的文件路径,获取到路径后赋值表单的属性
}
:file-list文件展示列表