常见文件下载方式

常见文件下载方式

方式 1 利用a标签下载文件

export function Demo() {
  const imgUrl = 'https://w.wallhaven.cc/full/3l/wallhaven-3l2ldd.png';

  return (
    <div>
      <a
        href={imgUrl}
        download
      >
        下载文件
      </a>
    </div>
  );
}

方式 2 使用 BlobURL.createObjectURL

async function downloadFile(url) {
  const response = await fetch(url);
  const data = await response.blob();
  const downloadUrl = URL.createObjectURL(data);
  const a = document.createElement('a');
  a.href = downloadUrl;
  a.download = 'file_name';
  a.click();

  URL.revokeObjectURL(downloadUrl);
}

downloadFile('https://w.wallhaven.cc/full/3l/wallhaven-3l2ldd.png');

方式 3 使用FormDataXMLHttpRequest

function downloadFile(url) {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'blob';

  xhr.onload = function () {
    if (this.status === 200) {
      const downloadUrl = URL.createObjectURL(this.response);
      const a = document.createElement('a');
      a.href = downloadUrl;
      a.download = 'file_name';
      a.click();

      URL.revokeObjectURL(downloadUrl);
    }
  };

  xhr.send();
}

downloadFile('https://w.wallhaven.cc/full/3l/wallhaven-3l2ldd.png');