記錄使用blob對象接收java后台文件流並下載為xlsx格式的詳細過程,關鍵部分代碼如下。
首先在java后台中設置response中的參數:
public void exportExcel(HttpServletResponse response, String fileName, String sheetName, List<String> titleRow, List<List<String>> dataRows) { OutputStream out = null; try { // 設置瀏覽器解析文件的mime類型,如果js中已設置,這里可以不設置 // response.setContentType("application/vnd.ms-excel;charset=gbk"); // 設置此項,在IE瀏覽器中下載Excel文件時可彈窗展示文件下載 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); // 允許瀏覽器訪問header中的FileName response.setHeader("Access-Control-Expose-Headers", "FileName"); // 設置FileName,轉碼防止中文亂碼 response.setHeader("FileName", URLEncoder.encode(fileName, "UTF-8")); out = response.getOutputStream(); ExcelUtils.createExcelStream(out, sheetName, titleRow, dataRows); out.close(); } catch (Exception e) { if (Objects.nonNull(out)) { try { out.close(); } catch (IOException e1) { log.error("導出失敗", e); } } throw Exceptions.fail(ErrorMessage.errorMessage("500", "導出失敗")); } }
此時在瀏覽器的調試面板中可以看到導出接口的response header參數如下:
access-control-allow-credentials: true access-control-allow-methods: GET,POST,PUT,DELETE,OPTIONS access-control-allow-origin: http://local.dasouche-inc.net:8081 access-control-expose-headers: FileName connection: close content-type: application/vnd.ms-excel;charset=gbk date: Sun, 29 Mar 2020 10:59:54 GMT filename: %E4%B8%BB%E6%92%AD%E5%88%97%E8%A1%A8166296222340726.xlsx
接下來我們在前端代碼中獲取文件流:
handleExport = () => { axios.post(`下載文件的接口請求路徑`, {}, { params: { 參數名1: 參數值1, 參數名2: 參數值2 }, // 設置responseType對象格式為blob responseType: "blob" }).then(res => { // 創建下載的鏈接 const url = window.URL.createObjectURL(new Blob([res.data], // 設置該文件的mime類型,這里對應的mime類型對應為.xlsx格式 {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})); const link = document.createElement('a'); link.href = url; // 從header中獲取服務端命名的文件名 const fileName = decodeURI(res.headers['filename']); link.setAttribute('download', fileName); document.body.appendChild(link); link.click(); }); };