如何为 HTTP GET 请求设置标头并触发文件下载?

2022-01-17 00:00:00 http-headers download javascript ajax

更新 20140702:

  • 解决方案
  • 博文中的详细答案

(但我将其他答案之一标记为已接受,而不是我自己的,因为它让我走到了一半,并奖励努力)

(but I'm marking one of the other answers as accepted instead of my own, as it got me halfway there, and to reward the effort)

似乎无法通过 <a href="..."> 的链接设置 HTTP 请求标头,只能使用 XMLHttpRequest.

It appears that setting a HTTP request header is not possible through links with <a href="...">, and can only be done using XMLHttpRequest.

但是,链接到的 URL 是一个应该下载的文件(浏览器不应导航到其 URL),我不确定这是否可以使用 AJAX 完成.

However, the URL linked to is a file that should be downloaded (browser should not navigate to its URL), and I am not sure is this can be done using AJAX.

另外,返回的文件是二进制文件,AJAX 不适用于此.

Additionally, the file being returned is a binary file, and AJAX is not intended for that.

如何使用添加了自定义标头的 HTTP 请求触发文件下载?

How would one go about triggering a file download with a HTTP request that has a custom header added to it?

修复断开的链接

推荐答案

试试

html

<!-- placeholder , 
    `click` download , `.remove()` options ,
     at js callback , following js 
-->
<a>download</a>

js

        $(document).ready(function () {
            $.ajax({
                // `url` 
                url: '/echo/json/',
                type: "POST",
                dataType: 'json',
                // `file`, data-uri, base64
                data: {
                    json: JSON.stringify({
                        "file": "data:text/plain;base64,YWJj"
                    })
                },
                // `custom header`
                headers: {
                    "x-custom-header": 123
                },
                beforeSend: function (jqxhr) {
                    console.log(this.headers);
                    alert("custom headers" + JSON.stringify(this.headers));
                },
                success: function (data) {
                    // `file download`
                    $("a")
                        .attr({
                        "href": data.file,
                        "download": "file.txt"
                    })
                        .html($("a").attr("download"))
                        .get(0).click();
                    console.log(JSON.parse(JSON.stringify(data)));
                },
                error: function (jqxhr, textStatus, errorThrown) {
                  console.log(textStatus, errorThrown)
                }
            });
        });

jsfiddle http://jsfiddle.net/guest271314/SJYy3/

相关文章