Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
169
rated 0 times [  173] [ 4]  / answers: 1 / hits: 149127  / 9 Years ago, mon, january 4, 2016, 12:00:00

I want to download a pdf file for jquery ajax response. Ajax response contains pdf file data. I tried this solution. My code is given below but I always get a blank pdf.



$(document).on('click', '.download-ss-btn', function () {

$.ajax({
type: POST,
url: 'http://127.0.0.1:8080/utils/json/pdfGen',
data: {
data: JSON.stringify(jsonData)
}

}).done(function (data) {
var blob = new Blob([data]);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = Sample.pdf;
link.click();
});


});

More From » jquery

 Answers
13

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();
}
});

[#63853] Thursday, December 31, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aidan

Total Points: 72
Total Questions: 95
Total Answers: 121

Location: Uzbekistan
Member since Sat, Feb 27, 2021
3 Years ago
aidan questions
Mon, Oct 11, 21, 00:00, 3 Years ago
Wed, Sep 29, 21, 00:00, 3 Years ago
Sun, Sep 5, 21, 00:00, 3 Years ago
Thu, Jan 16, 20, 00:00, 4 Years ago
;