使用场景:前端调用接口然后触发浏览器下载
后端代码
/**
* 文件下载
*
* @param id 文件id
* @return
*/
@GetMapping("/download/{id}")
public ResponseEntity<?> download(@PathVariable(value = "id") String id) {
// 通过id获取文件信息
FileManageViewModel viewModel = fileManageService.getObjectByKey(id);
// 处理文件名中文乱码问题
String fileName = new String(viewModel.getFileName().getBytes(), StandardCharsets.ISO_8859_1) ;
// 设置响应头
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
// 获取文件流(根据具体的场景获取)
InputStream inputStream = .......;
return ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(new InputStreamResource(inputStream));
}