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

How to Download Files Using window.fetch()?

Linda Hamilton
Release: 2024-10-23 07:29:01
Original
502 people have browsed it

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>
Copy after login

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>
Copy after login

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!

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!