需求:vue直接下载后台返回Excel文件
- 请求后台文件的时候需加入
responseType:'application/json'; application/octet-stream',headers:{ContentType: "application/json; application/octet-stream"}
export const allStaffHoursTable = (responseType, headers,params) => { return request({ url: '', method: 'post', responseType: responseType.responseType, headers, params }) }
- 封装下载文件共用代码
/** *fileData:后台数据 *filename:文件名 */ export const fileDownLoad = (fileData, filename) => { let blob = new Blob([fileData.data], { type: fileData.data.type //文件类型:"application/vnd.ms-excel" }); const fileName = `${filename}.xls`;//文件名称 let downloadElement = document.createElement("a"); let href = window.URL.createObjectURL(blob); //创建下载的链接 downloadElement.href = href; downloadElement.download = fileName; //下载后文件名 document.body.appendChild(downloadElement); downloadElement.click(); //点击下载 document.body.removeChild(downloadElement); //下载完成移除元素 window.URL.revokeObjectURL(href); //释放blob }
- 调用
let responseType = { responseType: "blob" }; let header = { ContentType: "application/json; application/octet-stream", }; allStaffCostsTable(data).then((res) => { fileDownLoad(res, "员工成本统计"); });
网友评论