一、首先检查nginx配置
浏览器不知道文件格式,会响应超时,造成下载两次,因为有些浏览器识别不了请求头,那么第一次http请求就会被认定为超时,接着跳转到另一个同样的请求,造成下载了两次文件。
博主主要遇到的Excel文件下载时遇到的问题,首先检查nginx配置有没有问题
nginx 中要加 链接超时时间设为60s
proxy_connect_timeout 60;
proxy_read_timeout 60;
proxy_send_timeout 60;
二、代码中在header中改变contentType类型为application/x-xls
当请求头指定MediaType.APPLICATION_OCTET_STREAM .*( 二进制流,不知道下载文件类型) 改变下载文件格式类型
为application/x-xls。
@RequestMapping("exportCardPwd")
@Log(title = "虚拟卡密导出模块",action = "导出每批次虚拟卡卡密")
public ResponseEntity<byte[]> exportCardPwd(HttpServletRequest request) throws IOException {
DBContextHolder.setDbType(DBContextHolder.DB_TYPE_R);
Long giftCardBatchId = null;
giftCardBatchId = Long.parseLong(request.getParameter("giftCardBatchId"));
List<GiftCard> giftCards = giftService.getGiftCardListByBatchId(giftCardBatchId);
File excelFile = giftService.exportCardPwd(PathUtil.getExcelFilesSaveRootPath(request), giftCards);
HttpHeaders headers = new HttpHeaders();
String fileName = new String(PathUtil.getNewExcelFileName().getBytes("UTF-8"), "iso-8859-1");// 为了解决中文名称乱码问题
headers.setContentDispositionFormData("attachment", fileName);
// headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentType(MediaType.valueOf("application/x-xls"));
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(excelFile), headers, HttpStatus.CREATED);
}
不同的格式有不同的ContentType, xls文档用application/x-xls
由此解决了每次下载两次请求。