Home  >  Article  >  Web Front-end  >  How to Download Files Using window.fetch() in Client-Side Code

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 07:27:01615browse

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

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!

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