从 Blob 下载任何文件

2025-06-10

从 Blob 下载任何文件

我将其发布在这里以便人们可以访问它,也许有人也会发现它很有用!

已弃用(参见下一个代码片段)

function downloadBlob(blob, name = 'file.txt') {
    if (
      window.navigator && 
      window.navigator.msSaveOrOpenBlob
    ) return window.navigator.msSaveOrOpenBlob(blob);

    // For other browsers:
    // Create a link pointing to the ObjectURL containing the blob.
    const data = window.URL.createObjectURL(blob);

    const link = document.createElement('a');
    link.href = data;
    link.download = name;

    // this is necessary as link.click() does not work on the latest firefox
    link.dispatchEvent(
      new MouseEvent('click', { 
        bubbles: true, 
        cancelable: true, 
        view: window 
      })
    );

    setTimeout(() => {
      // For Firefox it is necessary to delay revoking the ObjectURL
      window.URL.revokeObjectURL(data);
      link.remove();
    }, 100);
}

// Usage
downloadBlob(blob, 'myfile.pdf');
Enter fullscreen mode Exit fullscreen mode

注意
正如 Kaltu 在评论中指出的那样:出于安全原因,自 2019 年以来,“window.URL.createObjectURL()”似乎已被所有主流浏览器屏蔽。

这种方法应该能达到预期的效果:

function downloadBlob(blob, name = 'file.txt') {
  // Convert your blob into a Blob URL (a special url that points to an object in the browser's memory)
  const blobUrl = URL.createObjectURL(blob);

  // Create a link element
  const link = document.createElement("a");

  // Set link's href to point to the Blob URL
  link.href = blobUrl;
  link.download = name;

  // Append link to the body
  document.body.appendChild(link);

  // Dispatch click event on the link
  // This is necessary as link.click() does not work on the latest firefox
  link.dispatchEvent(
    new MouseEvent('click', { 
      bubbles: true, 
      cancelable: true, 
      view: window 
    })
  );

  // Remove link from body
  document.body.removeChild(link);
}

// Usage
let jsonBlob = new Blob(['{"name": "test"}'])
downloadBlob(jsonBlob, 'myfile.json');

Enter fullscreen mode Exit fullscreen mode

演示可以在这里找到

鏂囩珷鏉ユ簮锛�https://dev.to/nombrekeff/download-file-from-blob-21ho
PREV
CSS 中 Flutter 样式的解释 - LLF #5
NEXT
GitHub 上 Stars 最多的 13 个自托管项目