提取API以强制下载文件 [英] Fetch API to force download file

查看:69
本文介绍了提取API以强制下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调用一个API,以使用fetch API从服务器下载excel文件,但这并没有强制浏览器下载,这是我的标头响应:

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

在我用来调用API的代码下面:

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'
    }
})

推荐答案

仅当您导航到该资源时,浏览器才会显示下载的常规交互操作(显示另存为..."对话框等).通过示例更容易显示差异:

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. 通过XHR/Fetch在后台加载 http://mycompany.com/.
  1. window.location='http://mycompany.com/'
  2. Load http://mycompany.com/ via XHR/Fetch in the background.

在1.中,浏览器将加载页面 并显示其内容.在2.中,浏览器将加载原始数据并将其返回给您,但是您必须自己显示它.

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.

您必须对文件执行类似的操作.您拥有原始数据,但是必须自己显示"它.为此,您需要为下载的文件创建一个对象URL并导航到它:

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

这将获取响应,将其读取为blob,创建一个objectURL,打开它(在新选项卡中),然后撤消该URL.

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

有关对象URL的更多信息: https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL

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

这篇关于提取API以强制下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆