首页  >  文章  >  web前端  >  如何使用 Window.fetch() 下载文件并处理授权?

如何使用 Window.fetch() 下载文件并处理授权?

Barbara Streisand
Barbara Streisand原创
2024-10-23 07:32:01612浏览

How to Download a File with Window.fetch() and Handle Authorization?

使用 window.fetch() 下载文件

尝试使用 window.fetch() 下载文件时,then 块中要执行的适当步骤是如下所示:

.then((response) => {
  // Convert the response to a blob.
  return response.blob();
})
.then((blob) => {
  // Create a URL for the downloaded file.
  const fileURL = URL.createObjectURL(blob);

  // Navigate to the file URL to start downloading the file.
  window.location.assign(fileURL);
});

要获得仅使用 fetch API 的更简洁、高效的解决方案,请考虑以下代码:

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);
  });

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

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