通过ajax向后台请求excel文件
就是简单地通过ajax请求,jquery也行,axios也行,手写一个原生的ajax都可以。
但是要设置 responseType
为 'arraybuffer'
。
下载文件
设置Blob对象中的参数 { type: 'application/vnd.ms-excel' }
/**
* 下载Excel文件流
* @param {string} binaryData
* @param {string} fileName
*/
export const downloadExcel = (binaryData, fileName) => {
const a = document.createElement("a");
a.download = fileName;
a.style.display = "none";
a.href = URL.createObjectURL(new Blob([binaryData], { type: 'application/vnd.ms-excel' }));
document.body.appendChild(a);
a.click();
URL.revokeObjectURL(a.href);
document.body.removeChild(a);
}
binaryData 这个形参就是后台返回给我们的一堆二进制字符组成的文件,我们通过Blob对象和a标签对其进行下载。