setheader-download.js

/*http://stackoverflow.com/questions/24501358/how-to-set-a-header-for-a-http-get-request-and-trigger-file-download*/

by guest271314

HTML

<a>download</a>

JavaScript

$(document).ready(function () {
                $.ajax({
                    url: '/echo/json/',
                    type: "POST",
                    dataType: 'json',
                    data: {
                        json: JSON.stringify({
                            "file": "data:text/plain;base64,YWJj"
                        })
                    },
                    headers: {
                        "x-custom-header": 123
                    },
                    beforeSend: function (jqxhr) {
                        console.log(this.headers);
                        alert("custom headers" + JSON.stringify(this.headers));
                    },
                    success: function (data) {
                        $("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)
                    }
                });
            })