AJAX File Download with custom header AJAX File Download with custom header ajax ajax

AJAX File Download with custom header


Try using a element with data-* set to headers for request , $.ajax() with headers option set to a element data-headers object .

At $.ajax() success set a element href to response as Blob within objectURL, download attribute to file.name or temporary file name , call .click() on a element to activate "Save File" dialog .

$(document).ready(function() {  $("input[type=button]").click(function() {    // set `data-headers` object    var el = $("[data-headers]");    el.data("headers")["x-custom-headers"] = $("input[type=text]")[0].value       || el.data("headers")["x-custom-headers"];    $.ajax({      url: URL.createObjectURL(new Blob([$("textarea").val()], {        type: "text/plain"      })),      type: "GET",      // set `headers` to `a` element `data-headers` object      headers: $("[data-headers]").data("headers"),      beforeSend: function(jqxhr) {        console.log(this.headers);        alert("custom headers" + JSON.stringify(this.headers));      },      success: function(data, textStatus, jqxhr) {        var file = new Blob([data], {          "type": jqxhr.getResponseHeader("Content-Type")        });        console.log(data, file);        $("textarea, input[type=text]").val("");        $("a")          .attr({            "href": URL.createObjectURL(file),            "download": file.name || "file-" + $.now()          }).on("click", function() {            $(this).remove()          })          .get(0).click();      },      error: function(jqxhr, textStatus, errorThrown) {        console.log(textStatus, errorThrown)      }    });  })})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><textarea maxlength="5" placeholder="echo"></textarea><br><!-- set `x-custom-header` to `input type="text"` value --><input type="text" maxlength="5" placeholder="set request header" /><br /><input type="button" value="download" /><!-- set default `x-custom-header` to "123" --><a data-headers='{"x-custom-headers":"123"}'></a>