@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));
这个会导致下载的文件打不开,暂时不清楚原因