js使用fetch下载readableStream类型数据,axios不支持

发布时间 2023-07-27 10:22:35作者: 郭大蛋子

流操作API中的ReadableStream 接口呈现了一个可读取的二进制流操作。Fetch API通过Response 的属性body 提供了一个具体的 ReadableStream 对象。

axios只支持返回以下类型

"", "arraybuffer", "blob", "document", "json", "text"

使用fetch可以下载stream类型的文件。fetch也可以检测文件下载的进度

 

const requestOptions: any = {
        method: 'POST',
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            id: route.params.id
        })
    };
    fetch(import.meta.env.VITE_BASE_API + "/Api/StudentClient/DownloadMissionPdf", requestOptions).then(response => {
        response.blob().then(res => {
            const link = document.createElement('a');
            const body = document.querySelectorAll('body');
            link.href = window.URL.createObjectURL(res);
            link.download = detail.value.MissionName + ".pdf";
            link.style.display = 'none';
            body[0].appendChild(link);
            link.click();
            body[0].removeChild(link);
            window.URL.revokeObjectURL(link.href);
        })
    })