打包下載成.zip文件 項目背景 公司使用vue + SpringBoot實現批量下載功能 今天在調試批量下載這個功能。打包成.zip文件時,在返回給前端瀏覽器出現報錯信息: 後端報錯: ERROR c.c.p.c.e.BusinessExceptionHandler - java.io.IOExc ...
打包下載成.zip文件
項目背景
公司使用vue + SpringBoot實現批量下載功能
今天在調試批量下載這個功能。打包成.zip
文件時,在返回給前端瀏覽器出現報錯信息:
後端報錯:
ERROR c.c.p.c.e.BusinessExceptionHandler - java.io.IOException: 你的主機中的軟體中止了一個已建立的連接。
org.apache.catalina.connector.ClientAbortException: java.io.IOException: 你的主機中的軟體中止了一個已建立的連接。
找了好久的錯,發現瀏覽器的控制台有報錯信息
Access to XMLHttpRequest at 'http://...:8097/pcsms-admin/batchExport/pdf?vids=1e7ed541bdd6b9f5614cca14623f8681,8dfda9f7151745ad5aa5f0abc2c55d5c' from origin 'http://..:8001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
於是在後端中設置響應體,如 HttpServletResponse response :
response.setHeader("Access-Control-Allow-Origin","*");
緊接著又出現如下的報錯信息:
Access to XMLHttpRequest at 'http://...:8097/batchExport/pdf?vids=1e7ed541bdd6b9f5614cca14623f8681,8dfda9f7151745ad5aa5f0abc2c55d5c' from origin 'http://...:8001' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
在面向百度編程中,找到一個帖子有詳細的解釋--axios設置withCredentials導致“跨域”的解決方案。檢查前端配置果然有:
axios.defaults.withCredentials = true;
(一) 當前端配置withCredentials=true時, 後端配置Access-Control-Allow-Origin不能為*, 必須是相應地址
(二) 當配置withCredentials=true時, 後端需配置Access-Control-Allow-Credentials
(三) 當前端配置請求頭時, 後端需要配置Access-Control-Allow-Headers為對應的請求頭集合
於是我們可以採取方法一:axios.defaults.withCredentials = false;
在找其他解決方法時,找到一個可以不更改前端配置的方法二--Jquery Ajax設置withCredentials解決跨域請求,在response裡加上以下兩個header
response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
// response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
response.addHeader("Access-Control-Allow-Credentials","true");
最後,終於問題成功解決。
後端代碼:
- TestController
@RequestMapping(value = "/batchExport/pdf", method = RequestMethod.POST)
public void batchExportPdf(HttpServletRequest request, HttpServletResponse response, @RequestParam("vids") String vids) throws Exception {
//獲取uavFileId,不進行xss過濾
// HttpServletRequest orgRequest = XssHttpServletRequestWrapper.getOrgRequest(request);
// String ids = orgRequest.getParameter("vids");
String[] vid = vids.split(",");
byte[] data = sopService.batchExportPdf(vid);
String fileName = URLEncoder.encode("批量下載PDF" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + ".zip", "UTF-8");
response.reset();
// 當前端配置withCredentials=true時, 後端配置Access-Control-Allow-Origin不能為*, 必須是相應地址
response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
// 這個若不起作用,使用下麵的"FileName"的
// response.addHeader("Access-Control-Expose-Headers","*");
response.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
// 設置在下載框預設顯示的文件名
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ";" + "filename*=utf-8''" + fileName);
response.setHeader("FileName", fileName);
// 讓axios放行指定的響應頭 https://blog.csdn.net/u012586326/article/details/125790079
response.addHeader("Access-Control-Expose-Headers","FileName");
// 寫明文件大小
response.addHeader("Content-Length", "" + data.length);
// 指明response的返回對象是文件流
response.setContentType("application/octet-stream; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
// 當前端配置withCredentials=true時, 後端需配置Access-Control-Allow-Credentials
response.addHeader("Access-Control-Allow-Credentials","true");
IOUtils.write(data, response.getOutputStream());
}
- TestService
/**
* 批量下載pdf
* @param vids
* @return
*/
byte[] batchExportPdf(String[] vids) throws Exception;
- TestServiceImpl
@Override
public byte[] batchExportPdf(String[] vids) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// 用於將數據壓縮成Zip文件格式
ZipOutputStream zipOut = new ZipOutputStream(outputStream);
FileInputStream inputStream = null;
List<String> deletePdf = new ArrayList<>();
List<FileInputStream> in = new ArrayList<>();
try {
for (String vid : vids) {
// 下載到本地
// PdfDTO包含:pdfPath(本地PDF路徑)、fileName(下載後的文件名(不含文件尾碼.pdf))
PdfDTO dto = exportPdfByVid(vid);
if (!ObjectUtils.isEmpty(dto)) {
zipOut.putNextEntry(new ZipEntry((Objects.requireNonNull(dto.getFileName())) + ".pdf"));
inputStream = new FileInputStream(new File(dto.getPdfPath()));
int len;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) != -1) {
zipOut.write(bytes, 0, len);
}
//關閉該zip文件中打開的項
zipOut.closeEntry();
deletePdf.add(dto.getPdfPath());
in.add(inputStream);
}
}
} catch (Exception e) {
log.error("批量下載時出現錯誤:" + e.toString());
throw new BusinessException("批量下載時出現錯誤:" + e.getMessage());
} finally {
try {
for (FileInputStream stream : in) {
stream.close();
}
// 關流
IOUtils.closeQuietly(zipOut);
} catch (IOException e) {
log.error("批量下載時流關閉異常:" + e.toString());
}
// 刪除源文件(我這裡是因為從數據伺服器下載了文件到本地,所以刪掉本地的)
File file = null;
for (String s : deletePdf) {
file = new File(s);
file.delete();
}
}
return outputStream.toByteArray();
}
參考:
https://blog.csdn.net/cckevincyh/article/details/81140443
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
https://blog.csdn.net/baidu_28068985/article/details/105558280
https://blog.csdn.net/HermitSun/article/details/100797223