Search code examples
javascriptfetch-api

How can I download a file using window.fetch?


If I want to download a file, what should I do in the then block below?

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

Note: The code is on the client-side.


Solution

  • I temporarily solve this problem by using download.js and blob.

    let download = require('./download.min');
    
    ...
    
    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(function(resp) {
        return resp.blob();
      }).then(function(blob) {
        download(blob);
      });
    }
    

    It's working for small files, but maybe not working for large files. I think I should dig Stream more.