我来梳理下载文件的流程:
-
Ajax 请求配置 responseType -
后端返回「二进制数据」或者 JSON -
新建立 new Blob 生成实例对象 -
使用 URL.createObjectURL 生成临时的 URL -
创建 A 标签执行下载
1、Ajax 请求配置
/*** XMLHttpRequest.responseType* 我用的是 axios*/axios.get(url, {responseType: \\\"blob\\\",//别忘记设置params: {}}).then(res => {console.log(res);})
new Blob(array [, options])
let htmlFragment = [\\\'<a id=\\\"a\\\"><b id=\\\"b\\\">hey!</b></a>\\\'];let myBlob = new Blob(htmlFragment, {type : \\\'text/html\\\'});
let blob = new Blob([res.data], {type: \\\'application/vnd.ms-excel\\\'});
let objectURL = window.URL.createObjectURL(blob);//创建下载的链接
//获取文件名let disposition = res.headers[\\\'content-disposition\\\'];let _name = disposition.split(\\\'filename=\\\')[1].split(\\\';\\\')[0];
//创建 A 标签,模拟点击var creatA = document.createElement(\\\"a\\\");creatA.href = url;document.body.appendChild(creatA);creatA.click();
要记得释放 createObjectURL 创建的临时链接。
想要实现下载 HTML 页面,如何设置?
var data = \\\"<div style=\\\'color:red;\\\'>This is a blob</div>\\\";var blob = new Blob([data], { type: \\\'text/html\\\' });var blobURL = URL.createObjectURL(blob);
推荐阅读:
JavaScript 性能测试
[1]https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/responseType
[2]https://wangdoc.com/javascript/bom/arraybuffer.html
[3]https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL
原创文章,作者:小道研究,如若转载,请注明出处:https://www.sudun.com/ask/34555.html