首页 > web前端 > js教程 > 正文

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

Linda Hamilton
发布: 2024-10-23 07:29:01
原创
502 人浏览过

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中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!