前端JS接收后端文件流实现文件下载


需求:接收后端返回的文件流导出Excel

自己项目中遇到过,亲测有效

情况一:无需传token

href:接口地址
queryValues:传参
export function batchExport(href, queryValues) {
const link = document.createElement('a');
link.href = `${href}?${qs.stringify(queryValues)}`;
link.download = '导出.xls';
link.click();
}

情况二:header中传token,兼容IE,360兼容模式,文件名不会乱码

decodeURIComponent(xmlHttp.getResponseHeader("content-disposition").split(";")[1].split("filename=")[1] //从header中获取文件名,需后端提供,如果是前端定义的文件名,可直接 link.download = '文件名XXX'
href:接口地址
queryValues:传参
export function batchExport(href, queryValues) {
let xmlHttp = null;
if (window.ActiveXObject) {
xmlHttp = new window.ActiveXObject('Microsoft.XMLHTTP');
} else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
if (xmlHttp != null) {
xmlHttp.ContentType = 'application/vnd.ms-excel';
xmlHttp.open('get', `${href}?${qs.stringify(queryValues)}`, true);
xmlHttp.setRequestHeader('token', getUserInfo().token);
xmlHttp.responseType = 'blob';
xmlHttp.send();
xmlHttp.onreadystatechange = doResult;
}

function doResult() {
let link = document.createElement('a');
link.style.display = 'none';
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
//兼容IE
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
let url = new Blob([xmlHttp.response], { type: 'application/vnd.ms-excel' });
window.navigator.msSaveOrOpenBlob(url, decodeURIComponent(xmlHttp.getResponseHeader("content-disposition").split(";")[1].split("filename=")[1]));
}else{
      //其他浏览器
let url = createObjectURL((new Blob([xmlHttp.response],
{ type: 'application/vnd.ms-excel' })));
//文件名
link.download = decodeURIComponent(xmlHttp.getResponseHeader("content-disposition").split(";")[1].split("filename=")[1]);
link.href = url;
link.click();
}
} else {
message.error('下载失败');
}
}
}
}

 每天进步一点点~

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM