有一个接口我看用js来写时就是返回的代码直接就打开了对话框,保存成了excel文件,我用axios要把返回的这代码直接保存成文件怎么来做??
try {
const res = await api(params);
const blob = new Blob([res]);
// 兼容edge不支持createObjectURL方法
if ("msSaveOrOpenBlob" in navigator) return window.navigator.msSaveOrOpenBlob(blob, tempName + fileType);
const blobUrl = window.URL.createObjectURL(blob);
const exportFile = document.createElement("a");
exportFile.style.display = "none";
exportFile.download = `${tempName}${fileType}`;
exportFile.href = blobUrl;
document.body.appendChild(exportFile);
exportFile.click();
// 去除下载对url的影响
document.body.removeChild(exportFile);
window.URL.revokeObjectURL(blobUrl);
} catch (error) {
console.log(error);
}
有个库叫 filesave
大概原理就是 download 属性和 createObjectURL