I want to send a request to a URL which provides me a file download dialog box. At the same time the server needs certain parameters in the request header. I want to insert a custom header in the request and get a file in response. Is there any way we can achieve this?
Downloading PDF File on Button Click using jQueryInside the DownloadFile JavaScript function, the URL of the File is passed as parameter to the jQuery AJAX function. Inside the jQuery AJAX function, using the XmlHttpRequest (XHR) call, the PDF file is downloaded as Byte Array (Binary Data).
The only way to add headers to a request from inside a browser is use the XmlHttpRequest setRequestHeader method. Using this with "GET" request will download the resource. The trick then is to access the resource in the intended way.
The headers are additional key-value pairs send along with ajax request using the XMLHttpRequest object. An asynchronous HTTP request to the server by using The ajax() function and by including the header it describes to the server what kind of response it accept.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With