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

查看:51
本文介绍了Fetch 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. 中,浏览器将加载页面显示其内容.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/en-US/docs/Web/API/URL/createObjectURL

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

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

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