Home  >  Article  >  Web Front-end  >  How Can I Download a File Using the Client-Side Fetch API?

How Can I Download a File Using the Client-Side Fetch API?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-23 07:28:29917browse

How Can I Download a File Using the Client-Side Fetch API?

How to Download a File Using Client-Side Fetch

When developing a web or mobile application, you may need to download files from a remote server to the user's device. With the introduction of the Fetch API, downloading files on the client-side has become much easier.

Consider the following code snippet:

<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(...);
}</code>

In this scenario, you have a Fetch request defined that retrieves a file from Google Drive. The question arises: what should you do in the then block to download the file?

A cleaner and more efficient approach to file downloading is demonstrated below, utilizing the Fetch API without relying on additional libraries.

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

This code snippet initializes a Fetch request with the appropriate URL and authorization header. It then uses the res.blob() method to retrieve the file's binary data. Afterward, it creates a temporary object URL for the file and assigns it to the window.location to trigger the download.

The above is the detailed content of How Can I Download a File Using the Client-Side Fetch API?. 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