Fetch API to force download file

柔情痞子 提交于 2019-11-29 11:31:41

The browser won't show the usual interaction for the download (display Save As... dialog, etc.), only if you navigate to that resource. It is easier to show the difference with an example:

  1. window.location='http://mycompany.com/'
  2. Load http://mycompany.com/ via XHR/Fetch in the background.

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

You have to do something similar with files. You have the raw data, but you have to "display" it yourself. To do this, you need to create an object-URL for your downloaded file and navigate 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);
    });

This fetches the response, reads it as a blob, creates an objectURL, opens it (in a new tab), then revokes the URL.

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

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.

I found another way to download and it will work on IE by using

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!