springboot文件下载接口怎么写
时间: 2023-11-02 15:47:53 浏览: 51
你可以使用Spring框架中的Resource类来实现文件下载接口。具体实现步骤如下:
1. 在Controller中定义下载接口
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@RequestParam String fileName) {
// TODO: 实现文件下载逻辑
}
2. 对文件进行读取和组装
Resource resource = new FileSystemResource(filePath + fileName);
if (resource.exists()) {
// TODO: 处理文件名中文乱码问题
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity.ok()
.headers(headers)
.contentLength(resource.contentLength()) //设置文件大小
.contentType(MediaType.parseMediaType("application/octet-stream")) //设置下载内容类型
.body(resource);
}
3. 返回ResponseEntity对象
最后,将读取到的文件资源对象Resource封装进ResponseEntity对象并返回即可。
注意:在实现文件下载接口时,需要注意文件名的乱码问题,需要设置Content-Disposition头部属性。此外,还需要添加缓存控制相关的HTTP头部属性。