Home  >  Article  >  Web Front-end  >  How to Download a File with Window.fetch() and Handle Authorization?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-23 07:32:01612browse

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

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

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!

Statement:
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