@GetMapping("/download/file")
@ResponseBody
public Callable<Response<String>> downloadFile(@RequestParam String fileId, @RequestParam String fileName, HttpServletResponse response) {
try{
byte[] bytes = fileService.download(fileId);
if (bytes == null || bytes.length == 0) {
return () -> Response.error(ResponseCode.EXCEPTION_CODE, "找不到文件");
}else {
response.setHeader("Content-disposition",
String.format("attachment; filename=%s", URLEncoder.encode(fileName, "UTF-8")));
IOUtils.write(bytes, response.getOutputStream());
response.getOutputStream().close();
return null;
}
}catch (Exception e) {
logger.error(e.toString());
return () -> Response.error(ResponseCode.EXCEPTION_CODE, e.getMessage());
}
}
导出excel头信息设置:
ServletOutputStream output = response.getOutputStream();
response.reset();
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-disposition", "attachment;filename="+fileName);
// response.addHeader("Content-length", String.valueOf(wb.getBytes().length));
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
wb.write(output);
output.close();
注意:千万不要设置这个头信息:
response.addHeader(“Content-length”, String.valueOf(wb.getBytes().length));
这个会导致下载的文件打不开,暂时不清楚原因
本文详细介绍了如何使用Spring Boot实现文件下载功能,包括处理文件不存在的情况,以及正确的响应头设置。同时,深入探讨了导出Excel的具体实现,强调了避免设置Content-length头的重要性,以防止下载文件无法打开的问题。

被折叠的 条评论
为什么被折叠?



