DEV Community

metaht tsai
metaht tsai

Posted on

使用 fetch 从后端下载文件,并通过浏览器自动触发保存。

async function downloadPdf(){
try {
// 1. 显示 loading
showLoading();

    // 2. 请求后端下载接口
    const response = await fetch("/download", {
        method: "GET"
    });

    // 3. 检查 HTTP 状态
    if (!response.ok) {
        throw new Error("Download failed");
    }

    // 4. 将 response 转成二进制文件对象
    const blob = await response.blob();

    // 5. 创建临时浏览器 URL
    const url = window.URL.createObjectURL(blob);

    // 6. 创建隐藏的 a 标签
    const a = document.createElement("a");

    // 7. 设置下载地址
    a.href = url;

    // 8. 设置下载文件名
    a.download = "report.pdf";

    // 9. 将 a 标签加入页面, 只是为了兼容老版本的浏览器
    document.body.appendChild(a);

    // 10. 自动触发点击
    a.click();

    // 11. 删除 a 标签, 只是为了兼容老版本的浏览器
    document.body.removeChild(a);

    // 12. 释放内存
    window.URL.revokeObjectURL(url);

    // 13. 隐藏 loading
    hideLoading();

} catch (error) {

    hideLoading();

    console.error(error);

    alert("Download failed");
}
Enter fullscreen mode Exit fullscreen mode

}

Top comments (0)