React獲取Java后臺文件流并下載Excel文件流程解析
記錄使用blob對象接收java后臺文件流并下載為xlsx格式的詳細過程,關(guān)鍵部分代碼如下。
首先在java后臺中設(shè)置response中的參數(shù):
public void exportExcel(HttpServletResponse response, String fileName, String sheetName, List<String> titleRow, List<List<String>> dataRows) { OutputStream out = null; try { // 設(shè)置瀏覽器解析文件的mime類型,如果js中已設(shè)置,這里可以不設(shè)置 // response.setContentType('application/vnd.ms-excel;charset=gbk'); // 設(shè)置此項,在IE瀏覽器中下載Excel文件時可彈窗展示文件下載 response.setHeader('Content-Disposition', 'attachment;filename=' + URLEncoder.encode(fileName, 'UTF-8')); // 允許瀏覽器訪問header中的FileName response.setHeader('Access-Control-Expose-Headers', 'FileName'); // 設(shè)置FileName,轉(zhuǎn)碼防止中文亂碼 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('導(dǎo)出失敗', e); } } throw Exceptions.fail(ErrorMessage.errorMessage('500', '導(dǎo)出失敗')); }}
此時在瀏覽器的調(diào)試面板中可以看到導(dǎo)出接口的response header參數(shù)如下:
access-control-allow-credentials: trueaccess-control-allow-methods: GET,POST,PUT,DELETE,OPTIONSaccess-control-allow-origin: http://local.dasouche-inc.net:8081access-control-expose-headers: FileNameconnection: closecontent-type: application/vnd.ms-excel;charset=gbkdate: Sun, 29 Mar 2020 10:59:54 GMTfilename: %E4%B8%BB%E6%92%AD%E5%88%97%E8%A1%A8166296222340726.xlsx
接下來我們在前端代碼中獲取文件流:
handleExport = () => { axios.post(`下載文件的接口請求路徑`, {}, { params: { 參數(shù)名1: 參數(shù)值1, 參數(shù)名2: 參數(shù)值2 }, // 設(shè)置responseType對象格式為blob responseType: 'blob' }).then(res => { // 創(chuàng)建下載的鏈接 const url = window.URL.createObjectURL(new Blob([res.data],// 設(shè)置該文件的mime類型,這里對應(yīng)的mime類型對應(yīng)為.xlsx格式{type: ’application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’})); const link = document.createElement(’a’); link.href = url; // 從header中獲取服務(wù)端命名的文件名 const fileName = decodeURI(res.headers[’filename’]); link.setAttribute(’download’, fileName); document.body.appendChild(link); link.click(); });};
至此就可以愉快地下載xlsx格式的文件啦~
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章: