分享

js原生xhr处理文件下载问题_xhr下载文件

 lichwoo 2023-05-10 发布于北京
function downLoadFile(url,params){ var xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.responseType = "blob"; // 返回类型blob xhr.onload = function () { if (xhr.status === 200) { const dispoition = xhr.getResponseHeader('Content-Disposition') || '' const nameStr = dispoition.split(';')[1] || '' const fileName = decodeURI(nameStr.split('=')[1] || '') console.log(fileName,'乱码') //decodeURI解码需要后端处理。文件类型固定可自定义名字 const blob = new Blob([xhr.response], { type: "text/html; charset=UTF-8" }) const a = document.createElement('a') a.href = URL.createObjectURL(blob) a.download = fileName //a.download = '历史数据.xlsx'; // 成功 a.click(); } else { //请求失败处理 } }; // 发送ajax请求 xhr.send(JSON.stringify(params)) } 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多