Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-10-23 07:32:01
Original
611 people have browsed it

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

Downloading a File with window.fetch()

When attempting to download a file using window.fetch(), the appropriate steps to take within the then block are as follows:

.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);
});
Copy after login

For a more concise and efficient solution using only the fetch API, consider the following code:

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);
  });
Copy after login

The above is the detailed content of How to Download a File with Window.fetch() and Handle Authorization?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!