最近在做一个功能,前端接收后端传过来的 excel 文件流,一种是使用了 axios 请求,一种是使用了 XMLHttpRequest ,在这里做一下记录。
axios方式
axios({
url: window.fdConfig.url[indexParams.index].export,
method: window.fdConfig.methodPost,
data: downloadPrams,
responseType: 'blob'
}).then(response => {
const blob = new Blob([response.data], {type: 'application/vnd.ms-excel'});
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
// 这里也可以自己从headers中获取文件名.
link.download = '导出excel.xlsx';
link.click();
}, error => {
console.log('导出excel出错');
});
这种方式需要注意的就是需要设置 responseType 为 blob。
XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.responseType = "blob";
xhr.setRequestHeader("Content-Type","application/json");
xhr.onload = () => {
if (xhr.status == 200) {
var blob = xhr.response;
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function (e) {
var a = document.createElement("a");
// 这里也可以自己从headers中获取文件名.
a.download = '导出excel.xlsx';
a.href = e.target.result;
$("body").append(a);
a.click();
$(a).remove();
};
} else {
console.log('导出excel出错');
}
}
xhr.send(jsonData);
定义 responseType='blob' , 是读取文件成功的关键,这样设置可以解决下载文件乱码的问题。