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

How to Download Files Using window.fetch() in Client-Side Code

Linda Hamilton
Release: 2024-10-23 07:27:01
Original
614 people have browsed it

How to Download Files Using window.fetch() in Client-Side Code

Downloading Files Using window.fetch()

In the client-side code snippet you provided, you can complete the then block to download a file as follows:

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 => res.blob()).then(blob => {
    // Create a URL for the Blob and assign it to the window location
    var file = window.URL.createObjectURL(blob);
    window.location.assign(file);
  });
}
Copy after login

This code offers a more efficient and library-free solution compared to using external libraries. It leverages the window.fetch() API to retrieve the file from the provided URL. The res.blob() method converts the response into a Blob object, representing the file data.

Next, we create a URL for the Blob using window.URL.createObjectURL() and assign it to the window.location property. This initiates a download action for the file, without the need for additional libraries or complex processing.

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