Fetch API to force download file

Viewed 27886

I'm calling an API to download excel file from the server using the fetch API but it didn't force the browser to download, below is my header response:

HTTP/1.1 200 OK Content-Length: 168667 
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet 
Server: Microsoft-IIS/8.5 
Content-Disposition: attachment; filename=test.xlsx 
Access-Control-Allow-Origin: http://localhost:9000 
Access-Control-Allow-Credentials: true 
Access-Control-Request-Method: POST,GET,PUT,DELETE,OPTIONS 
Access-Control-Allow-Headers: X-Requested-With,Accept,Content-Type,Origin 
Persistent-Auth: true 
X-Powered-By: ASP.NET 
Date: Wed, 24 May 2017 20:18:04 GMT

Below my code that I'm using to call the API :

this.httpClient.fetch(url, {
    method: 'POST',
    body: JSON.stringify(object),
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }
})
5 Answers

There are some handy libraries and to solve an issue that I had with CSV/text download I used FileSaver.

Example:

var saveAs = require('file-saver');

fetch('/download/urf/file', {
  headers: {
    'Content-Type': 'text/csv'
  },
  responseType: 'blob'
}).then(response => response.blob())
  .then(blob => saveAs(blob, 'test.csv'));

There is also download.js lib as explained here in this question.

You can do it like this using the below function

download(filename) {
 fetch(url , { headers })
 .then(response => response.blob())
 .then(blob => URL.createObjectURL(blob))
 .then(uril => {
 var link = document.createElement("a");
 link.href = uril;
 link.download = filename + ".csv";
 document.body.appendChild(link);
 link.click();
 document.body.removeChild(link);
 });
}

here I want to download a CSV file, So I add .csv to the filename.

My solution is based on @VINEE and @balazska solution. I wanted to avoid manipulating document.body or opening a new tab via window.open(url, '_blank');

return fetch(urlEndpoint, options)
  .then((res) => res.blob())
  .then((blob) => URL.createObjectURL(blob))
  .then((href) => {
    Object.assign(document.createElement('a'), {
      href,
      download: 'filename.csv',
    }).click();
  });
Related