Fetch API to force download download file

I call the API to download the excel file from the server using the Fetch API, but it did not force the browser to load, 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 is my code that I use to call the API:

 this.httpClient.fetch(url, { method: 'POST', body: JSON.stringify(object), headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }) 
+3
source share
3 answers

The browser will not display the usual interaction for downloading (display the "Save As ..." dialog, etc.) only if you go to this resource. Itโ€™s easier to show the difference with an example:

In 1. the browser will load the page and display its contents. In 2. the browser will download the raw data and return it to you, but you must display it yourself.

You should do something similar with files. You have raw data, but you must โ€œdisplayโ€ it yourself. To do this, you need to create an object URL for the downloaded file and go to it:

 this.httpClient .fetch(url, {method, body, headers}) .then(response => response.blob()) .then(blob => URL.createObjectURL(blob)) .then(url => { window.open(url, '_blank'); URL.revokeObjectURL(url); }); 

Executes the response, reads it as a blob, creates an url object, opens it (in a new tab), and then cancels the URL.

More about object URLs: https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

+3
source

I found a different download method and it will work in IE using

https://www.npmjs.com/package/downloadjs

0
source

There are several handy libraries that can solve this problem. To solve the problem that I encountered downloading CSV / text, I used FileSaver .

Example:

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

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

0
source

All Articles