首页  >  文章  >  web前端  >  如何使用客户端 Fetch API 下载文件?

如何使用客户端 Fetch API 下载文件?

Patricia Arquette
Patricia Arquette原创
2024-10-23 07:28:29917浏览

How Can I Download a File Using the Client-Side Fetch API?

如何使用客户端获取下载文件

开发 Web 或移动应用程序时,您可能需要从远程服务器到用户的设备。随着 Fetch API 的引入,在客户端下载文件变得更加容易。

考虑以下代码片段:

<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(...);
}</code>

在这个场景中,您有一个 Fetch 请求定义从 Google Drive 检索文件。问题出现了:您应该在 then 块中做什么来下载文件?

下面演示了一种更干净、更高效的文件下载方法,利用 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>

此代码片段使用适当的 URL 和授权标头初始化 Fetch 请求。然后,它使用 res.blob() 方法检索文件的二进制数据。然后,它为文件创建一个临时对象 URL,并将其分配给 window.location 以触发下载。

以上是如何使用客户端 Fetch API 下载文件?的详细内容。更多信息请关注PHP中文网其他相关文章!

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