In this article I will explain with an example, how to download file in AJAX Response (Success) using jQuery.
The file will be downloaded as BLOB using jQuery AJAX and XmlHttpRequest (XHR) request and then the file will be downloaded using the Response inside the Success event handler of jQuery AJAX function.
Location of Files
The PDF file are stored in a folder named Files inside the project directory.
Note: You can also set URL of the PDF which can belong to either same server or any other server location.
Downloading PDF File on Button Click using jQuery
When the Download Button is clicked, the DownloadFile JavaScript function is called.
Inside 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).
Note: The XmlHttpRequest (XHR) call is only supported in jQuery version 3.0 and higher.
Finally, the received Byte Array (Binary Data) is converted to BLOB object and the File is downloaded in Browser.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<input type="button" value="Download PDF File" onclick="DownloadFile('Sample.pdf')" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script type="text/javascript">
function DownloadFile(fileName) {
//Set the File URL.
var url = "Files/" + fileName;
$.ajax({
url: url,
cache: false,
xhr: function () {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 2) {
if (xhr.status == 200) {
xhr.responseType = "blob";
} else {
xhr.responseType = "text";
}
}
};
return xhr;
},
success: function (data) {
//Convert the Byte Data to BLOB object.
var blob = new Blob([data], { type: "application/octetstream" });
//Check the Browser type and download the File.
var isIE = false || !!document.documentMode;
if (isIE) {
window.navigator.msSaveBlob(blob, fileName);
} else {
var url = window.URL || window.webkitURL;
link = url.createObjectURL(blob);
var a = $("<a />");
a.attr("download", fileName);
a.attr("href", link);
$("body").append(a);
a[0].click();
$("body").remove(a);
}
}
});
};
</script>
</body>
</html>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers only in versions that support HTML5.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads