Home  >  Article  >  Web Front-end  >  How to Download Files Using window.fetch()?

How to Download Files Using window.fetch()?

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 07:29:01503browse

How to Download Files Using window.fetch()?

Downloading Files with window.fetch()

When it comes to downloading files using the window.fetch() API, you'll need to chain a then() block to the fetch() call to handle the response. Here's how you can do it:

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

In the then() block, you can typically use the following steps to download the file:

  1. Convert the response to a blob: res.blob().then(blob => {});
  2. Create a URL for the blob: var file = window.URL.createObjectURL(blob);
  3. Assign the URL to the window.location to trigger a download: window.location.assign(file);

Here's a shorter and more efficient alternative that uses only the 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>

The above is the detailed content of How to Download Files Using window.fetch()?. 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