使用response下載沒反應
阿新 • • 發佈:2019-01-11
response.reset();
File excelFile = new File(filePath);
// 1.設定檔案ContentType型別,這樣設定,會自動判斷下載檔案型別
response.setContentType("application/octet-stream");
// 2.設定檔案頭:處理檔名編碼,防止不同瀏覽器中文的檔名出現亂碼
String headerValue = "attachment;";
String fileName = "體驗館報名名單.xlsx";
headerValue += " filename=\"" + fileOperationService.encodeURIComponent(fileName) + "\";";
headerValue += " filename*=utf-8''" + fileOperationService.encodeURIComponent(fileName);
response.setHeader("Content-Disposition", headerValue);
response.addHeader("Content-Length", String.valueOf(excelFile.length()));
// 通過檔案流下載
try {
InputStream ins = new BufferedInputStream(new FileInputStream(excelFile));
byte[] buffer = new byte[ins.available()];
ins.read(buffer);
ins.close();
OutputStream ous = new BufferedOutputStream(response.getOutputStream());
ous.write(buffer);
ous.flush();
ous.close();
} catch (IOException e) {
e.printStackTrace();
File excelFile = new File(filePath);
// 1.設定檔案ContentType型別,這樣設定,會自動判斷下載檔案型別
response.setContentType("application/octet-stream");
// 2.設定檔案頭:處理檔名編碼,防止不同瀏覽器中文的檔名出現亂碼
String headerValue = "attachment;";
String fileName = "體驗館報名名單.xlsx";
headerValue += " filename=\"" + fileOperationService.encodeURIComponent(fileName) + "\";";
headerValue += " filename*=utf-8''" + fileOperationService.encodeURIComponent(fileName);
response.setHeader("Content-Disposition", headerValue);
response.addHeader("Content-Length", String.valueOf(excelFile.length()));
// 通過檔案流下載
try {
InputStream ins = new BufferedInputStream(new FileInputStream(excelFile));
byte[] buffer = new byte[ins.available()];
ins.read(buffer);
ins.close();
OutputStream ous = new BufferedOutputStream(response.getOutputStream());
ous.write(buffer);
ous.flush();
ous.close();
} catch (IOException e) {
e.printStackTrace();
}
ajax請求只是個“字元型”的請求,即請求的內容是以文字型別存放的。檔案的下載是以二進位制形式進行的,雖然可以讀取到返回的response,但只是讀取而已,是無法執行的。
解決方案,不用ajax:
window.location.href=_contextPath + "/signUp/exportSignUpList.do";