后台返回的是 ResponseEntity<byte[]> 格式
1、需要加参数,header的,如下,如果不需要这些,可去掉
export const getFileExport = async (url) => { const headers = await getHeaders(); return await axios.get(url, { //downloadFiles 接口请求地址 params: {user: sessionStorage.getItem(TOKEN_SESSION_CONFIG.USER)}, headers: headers, responseType:'blob' }).then((rs) => { const blob = new Blob([rs.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }) const fileName = "用户导入模板.xlsx"; if ('download' in document.createElement('a')) { // 非IE下载 const elink = document.createElement('a'); elink.download = fileName; elink.style.display = 'none'; elink.href = URL.createObjectURL(blob); document.body.appendChild(elink); elink.click(); URL.revokeObjectURL(elink.href);// 释放 URL对象 document.body.removeChild(elink); } }).catch((error) => { console.log('文件下载失败', error); }); };
2、模拟form表单提交,该函数缺点好像是不能传header
export const getFileExport = async (url) => { let formElement = document.createElement('form'); formElement.style.display = "display:none;"; formElement.method = 'get'; formElement.action = url; formElement.target = 'callBackTarget'; let inputElement = document.createElement('input'); inputElement.type = 'hidden'; inputElement.name = "user" ; inputElement.value = sessionStorage.getItem(TOKEN_SESSION_CONFIG.USER); formElement.appendChild(inputElement); document.body.appendChild(formElement); formElement.submit(); document.body.removeChild(formElement); };
来源:oschina
链接:https://my.oschina.net/u/3677751/blog/4284066