小编典典

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

ajax

(但是我将其他答案之一标记为已接受,而不是我自己的答案,因为它使我半途而废,并以此来奖励自己的努力)


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

但是,链接到的URL是应下载的文件(浏览器不应导航至其URL),而且我不确定是否可以使用AJAX来完成。

此外,返回的文件是一个二进制文件,而AJAX并非用于此目的。

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

编辑:修复断开的链接


阅读 560

收藏
2020-07-26

共1个答案

小编典典

尝试

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/

2020-07-26