React獲取Java後臺檔案流並下載Excel檔案流程解析
阿新 • • 發佈:2020-06-17
記錄使用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=gbkdate: 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(); }); };
至此就可以愉快地下載xlsx格式的檔案啦~
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。