首页  >  文章  >  web前端  >  如何使用window.fetch()下载文件?

如何使用window.fetch()下载文件?

Linda Hamilton
Linda Hamilton原创
2024-10-23 07:29:01503浏览

How to Download Files Using window.fetch()?

使用 window.fetch() 下载文件

当使用 window.fetch() API 下载文件时,您需要链接一个 then( ) 阻止 fetch() 调用来处理响应。具体操作方法如下:

<code class="javascript">function downloadFile(token, fileId) {
  let url = `https://www.googleapis.com/drive/v2/files/${fileId}?alt=media`;
  return fetch(url, {
    method: 'GET',
    headers: {
      'Authorization': token
    }
  }).then(res => {
    // Handle the response here
  });
}</code>

在 then() 块中,您通常可以使用以下步骤来下载文件:

  1. 将响应转换为 blob : res.blob().then(blob => {});
  2. 为 blob 创建 URL:var file = window.URL.createObjectURL(blob);
  3. 分配用于触发下载的 window.location 的 URL:window.location.assign(file);

这里有一个更短、更高效的替代方案,仅使用 fetch API:

<code class="javascript">const url ='http://sample.example.file.doc'
const authHeader ="Bearer 6Q************" 

const options = {
  headers: {
    Authorization: authHeader
  }
};
fetch(url, options)
  .then(res => res.blob())
  .then(blob => {
    var file = window.URL.createObjectURL(blob);
    window.location.assign(file);
  });</code>

以上是如何使用window.fetch()下载文件?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn