萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JS 實現點擊下載文件:iframe 透明提交法

早期瀏覽器不支援 <a download>,利用隱藏 <iframe> 模擬下載:創建 iframe → 設 src 為文件 URL → 在 iframe 執行 execCommand('SaveAs')。

核心代碼

<a href="a.txt" id="dlLink" onclick="return saveFile()">點擊下載</a>

<script>
function saveFile(){
    const link = document.getElementById('dlLink');
    const iframeName = 'dlFrame';

    // 1. 確保 iframe 存在
    let iframe = window.frames[iframeName];
    if(!iframe){
        const el = document.createElement('iframe');
        el.name = iframeName;
        el.style.display = 'none';
        document.body.appendChild(el);
        iframe = window.frames[iframeName];
        // 給 iframe 一點時間初始化
        return setTimeout(saveFile, 1);
    }

    // 2. 觸發下載
    iframe.location.href = link.href;
    try{
        iframe.document.execCommand('SaveAs');
    }catch(e){
        // 非 IE 不支援 SaveAs,現代瀏覽器直接下載
    }
    return false; // 阻止 a 標簽默認跳轉
}
</script>

現代標準做法

<a href="file.pdf" download="自定義文件名.pdf">下載</a>
  • download 屬性指定保存文件名,同源策略下直接觸發下載。
  • 跨域文件需服務端設置 Content-Disposition: attachment 或代理下載。
  • Blob/ArrayBuffer + URL.createObjectURL 可下載動態生成內容(如 Canvas 圖片、JSON 導出)。

兼容性建議

iframe 方案僅用於極舊 IE 維護。新項目直接用 <a download> + Blob 下載,代碼簡潔、無副作用、標準化。

copyright © 萬盛學電腦網 all rights reserved