JS下载文件方法
在下载文件或者导出文件的时候,有时候会返回blob文件流的数据,而不是返回URL地址。
应用在window挂载下载文件的方法
一般的xhr请求
function sendRequest() {
// 发送请求
var xhr = new XMLHttpRequest();
xhr.open('get', 'http://10.3.124.171:11520/test/testcss' );
xhr.setRequestHeader('Access-Control-Allow-Origin', '*')
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const res = xhr.responseText;
console.log('res: ', res);
}
}
xhr.onerror = function (error) {
console.log('error: ', error);
}
}
上面代码处理一般的xhr请求足够满足,即返回类型为DOMString的,但是处理文件类型是有问题的。
responseType:设置该值能够改变响应类型,告诉服务器你期望的响应格式。
xhr.response的数据类型
代码
const downloadFile = (url, name) => {
console.log(url);
const xhr = new XMLHttpRequest();
console.log(xhr, "xhr");
xhr.open("GET", url, true);
xhr.setRequestHeader("token", localStorage.getItem("token"));
xhr.responseType = "blob";
xhr.onload = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
// 数据为DOMString格式的用xhr.responseText
const res = xhr.response;
// 通过Blob对象,我们在前端代码中就可以动态生成文件,提供给浏览器下载。
const u = window.URL.createObjectURL(new Blob([res]));
const a = document.createElement("a");
a.download = name; // 设置文件名
a.href = u;
a.style.display = "none";
document.body.appendChild(a);
a.click();
a.remove();
}
};
xhr.send();
};