需求需要将后端返回的列表数据下载到本地,查询资料发现采用blob文件流下载
/* 批量文件下载 */export function listFileDownload(params) { api({ url: '/mweb/mcif.TellerListDownLoad.do', method: 'post', headers: { 'Content-Type': 'application/x-www-form-urlencoded;application/octet-stream' }, transformRequest: [() => { let ret = '' for (let i in params) { ret = encodeURIComponent(i) '=' encodeURIComponent(params[i]) '&' } return ret }], data: params, responseType: 'blob' }).then(res => { if ('msSaveOrOpenBlob' in navigator) { var data = res var blob = new Blob([data], { type: 'application/vnd.ms-excel' }) window.navigator.msSaveOrOpenBlob(data, 'MSPOptJnl' new Date().getTime() '.xls') } else { let blob = new Blob([res]) let downloadElement = document.createElement('a') let href = URL.createObjectURL(blob) downloadElement.href = href downloadElement.download = 'mcif.TellerList_' new Date().getTime() '.xls' document.body.appendChild(downloadElement) downloadElement.click() document.body.removeChild(downloadElement) window.URL.revokeObjectURL(href) } }) .catch(err => { console.log(err); })}
2、后端列返回的是纯数组,采用模板拼接数据,IE采用msSaveBlob进行下载,chorme还是采用模拟点击,具体如下
/* 文件下载 */export function fileDownload(params) { api({ url: 'msp.MspTransOprtJnl.do', method: 'post', data: params, }).then(res => { let str = `机构编号,机构名称,MSP客户编号,客户姓名,操作内容,操作起止日期\n`; let name = ['TransDeptId', 'TransDeptName', 'OptId', 'OptName', 'TransBusGroupName', 'TransDate'] // 增加\t为了不让表格显示科学计数法或者其他格式 for (let i = 0; i < res.List.length; i ) { for (const key in res.List[i]) { for (let j = 0; j < name.length; j ) { if (key == name[j]) { str = `${res.List[i][key] '\t'},`; } } } str = '\n'; } if ('msSaveOrOpenBlob' in navigator) { var blob = new Blob([decodeURIComponent(encodeURI(str))], { type: "text/csv;charset=utf-8;" }); navigator.msSaveBlob(blob, 'MSPOptJnl' new Date().getTime() '.xls');//filename文件名包括扩展名,下载路径为浏览器默认路径 } else { // encodeURIComponent解决中文乱码 const uri = 'data:text/csv;charset=utf-8,\ufeff' encodeURIComponent(str); // 通过创建a标签实现 const link = document.createElement("a"); link.href = uri; // 对下载的文件命名 link.download = 'MSPOptJnl' new Date().getTime() '.xls'; link.click(); } }) .catch(err => { console.log(err); })}
来源:https://www.icode9.com/content-4-895901.html
联系客服