<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: metaht tsai</title>
    <description>The latest articles on Forem by metaht tsai (@metaht_tsai_99e1eba6c7d4f).</description>
    <link>https://forem.com/metaht_tsai_99e1eba6c7d4f</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3924409%2F1ba9b9b4-6259-4508-a4f9-33bc03abb780.png</url>
      <title>Forem: metaht tsai</title>
      <link>https://forem.com/metaht_tsai_99e1eba6c7d4f</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/metaht_tsai_99e1eba6c7d4f"/>
    <language>en</language>
    <item>
      <title>使用 fetch 从后端下载文件，并通过浏览器自动触发保存。</title>
      <dc:creator>metaht tsai</dc:creator>
      <pubDate>Mon, 11 May 2026 07:43:07 +0000</pubDate>
      <link>https://forem.com/metaht_tsai_99e1eba6c7d4f/shi-yong-fetch-cong-hou-duan-xia-zai-wen-jian-bing-tong-guo-liu-lan-qi-zi-dong-hong-fa-bao-cun--332k</link>
      <guid>https://forem.com/metaht_tsai_99e1eba6c7d4f/shi-yong-fetch-cong-hou-duan-xia-zai-wen-jian-bing-tong-guo-liu-lan-qi-zi-dong-hong-fa-bao-cun--332k</guid>
      <description>&lt;p&gt;async function downloadPdf(){&lt;br&gt;
    try {&lt;br&gt;
        // 1. 显示 loading&lt;br&gt;
        showLoading();&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    // 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");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

</description>
      <category>frontend</category>
      <category>javascript</category>
      <category>tutorial</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
