axios把返回的代码保存成文件?

有一个接口我看用js来写时就是返回的代码直接就打开了对话框,保存成了excel文件,我用axios要把返回的这代码直接保存成文件怎么来做??
image.png

阅读 1.5k
2 个回答

有个库叫 filesave

大概原理就是 download 属性和 createObjectURL

新手上路,请多包涵
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);
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进