Force download a pdf link using javascript/ajax/jquery
Use the HTML5 "download" attribute
<a href="iphone_user_guide.pdf" download="iPhone User's Guide.PDF">click me</a>
2021 Update: Now supported in all major browsers! see: caniuse.com/#search=download
If you need to support older browsers, or you're looking for an actual javascript solution (for some reason) please see lajarre's answer
Download pdf file using jquery ajax
jQuery has some issues loading binary data using AJAX requests, as it does not yet implement some HTML5 XHR v2 capabilities, see this enhancement request and this discussion
Given that, you have one of two solutions:
First solution, abandon JQuery and use XMLHTTPRequest
Go with the native HTMLHTTPRequest, here is the code to do what you need
var req = new XMLHttpRequest();
req.open("GET", "/file.pdf", true);
req.responseType = "blob";
req.onload = function (event) {
var blob = req.response;
console.log(blob.size);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Dossier_" + new Date() + ".pdf";
link.click();
};
req.send();
Second solution, use the jquery-ajax-native plugin
The plugin can be found here and can be used to the XHR V2 capabilities missing in JQuery, here is a sample code how to use it
$.ajax({
dataType: 'native',
url: "/file.pdf",
xhrFields: {
responseType: 'blob'
},
success: function(blob){
console.log(blob.size);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Dossier_" + new Date() + ".pdf";
link.click();
}
});
Download and open PDF file using Ajax
You don't necessarily need Ajax for this. Just an <a>
link is enough if you set the content-disposition
to attachment
in the server side code. This way the parent page will just stay open, if that was your major concern (why would you unnecessarily have chosen Ajax for this otherwise?). Besides, there is no way to handle this nicely acynchronously. PDF is not character data. It's binary data. You can't do stuff like $(element).load()
. You want to use completely new request for this. For that <a href="pdfservlet/filename.pdf">pdf</a>
is perfectly suitable.
To assist you more with the server side code, you'll need to tell more about the language used and post an excerpt of the code attempts.
Download pdf file from ajax response
Any idea on how to optimize it for all modern browsers?
Yes, I can give you a solution tested on windows 10 with IE11, Firefox 47 and Chrome 52. Nothing for Microsoft Edge at the moment.
At the beginning you need to distinguish if you are on IE or the other two browsers. This because on IE11 you can use:
window.navigator.msSaveBlob(req.response, "PdfName-" + new Date().getTime() + ".pdf");
For the other two browsers your code works on Chrome but not on Firefox because you did not append the element to the document body.
So the corrected code is:
var req = new XMLHttpRequest();
req.open("POST", "/servicepath/Method?ids=" + ids, true);
req.responseType = "blob";
req.onreadystatechange = function () {
if (req.readyState === 4 && req.status === 200) {
// test for IE
if (typeof window.navigator.msSaveBlob === 'function') {
window.navigator.msSaveBlob(req.response, "PdfName-" + new Date().getTime() + ".pdf");
} else {
var blob = req.response;
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "PdfName-" + new Date().getTime() + ".pdf";
// append the link to the document body
document.body.appendChild(link);
link.click();
}
}
};
req.send();
Download a pdf file using https path in javascript
One of the ways that were already mentioned would be by appending an invisible <iframe>
and appending a URL
in JS but there will be some security errors that will creep up.
In my method below, I have used
Axios.js
to allow me to safely download the file which also includes Promises
.Axios.JS CDN:
<script
src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
JS
function DownloadFromUrl(url, mime) {
axios({
url: url,
method: 'GET',
responseType: 'blob', // important
}).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.' + mime);
document.body.appendChild(link);
link.click();
});
}
$.ajax({
type: "POST",
url: "/Reporting/ReportAPI",
data: '{PatientId:"BH0012"}',
contentType: "application/json,utf=charset-8",
datatype: "JSON",
success: function(response) {
// Response = URL
// Mime = File Type - pdf, jpeg, png, bmp, exe, js...
DownloadFromUrl(response, "pdf");
}
});
Make sure to wrap the MIME
parameter as a string, or change the code above to validate the MIME Type
Here's JSFiddle: https://jsfiddle.net/5mnethL1/2/
Related Topics
How to Get the Name of the Current Windows User in JavaScript
How to Reset the Bootstrap Modal When It Gets Closed and Open It Fresh Again
Add Two Numbers and Display Result in Textbox With JavaScript
How to Detect Browser Back Button Click Event Using Angular
How to Import File from Public Folder in React Application
Retrieving Keys from Json Array Key-Value Pair Dynamically - JavaScript
How to Print Star Pattern in JavaScript in a Very Simple Manner
How to Merge an Array of Objects With Same Keys in Es6 JavaScript
Amount of All Goals of One Team (From Json)
Detect If a Field Is Updated With JavaScript or Jquery
Select Value of Input Element Inside HTML Table Using Jquery
Force Download a Pdf Link Using Javascript/Ajax/Jquery
Node.Js Call Function If Button Clicked
How to Change Text Value Upon Button Press in React Native
Getting Internal Server Error (500) - Codeigniter
Observe Localstorage Changes in Js
How to Force Update Child Component from Parent Component in Reactjs