Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
116
rated 0 times [  119] [ 3]  / answers: 1 / hits: 17206  / 6 Years ago, sat, september 1, 2018, 12:00:00

I have Java REST webservice that returns documents as byte array, I need to write JavaScript code to get the webservice's response and write it to a file in order to download that file as PDF Kindly see a screen shot of the webservice's response and see my sample code this code downloads a corrupted PDF file.


var data = new FormData();
data.append('PARAM1', 'Value1');
data.append('PARAM2', 'Value2');
var xhr = new XMLHttpRequest();
xhr.open('POST', 'SERVICEURL');
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
xhr.onload = function() {

console.log('Response text = ' + xhr.responseText);
console.log('Returned status = ' + xhr.status);


var arr = [];
arr.push(xhr.responseText);

var byteArray = new Uint8Array(arr);
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob(byteArray, { type: 'application/octet-stream' }));
a.download = "tst.pdf";
// Append anchor to body.
document.body.appendChild(a)
a.click();
// Remove anchor from body
document.body.removeChild(a)

};
xhr.send(data);

enter


More From » arrays

 Answers
18

Since you are requesting a binary file you need to tell XHR about that otherwise it will use the default "text" (UTF-8) encoding that will interpret pdf as text and will mess up the encoding. Just assign responseType property a value of 'blob' or the MIME type of pdf


var xhr = new XMLHttpRequest();
xhr.responseType = 'blob'; // tell XHR that the response will be a pdf file

// OR xhr.responseType = 'application/pdf'; if above doesn't work

And you will access it using response property and not responseText.
So you will use arr.push(xhr.response); and it will return you a Blob.


If this doesn't work, inform me will update another solution.


Update:


var xhr = new XMLHttpRequest();
xhr.responseType = 'blob'; // tell XHR that the response will be a pdf file
xhr.onload = function() {
var blob = this.response;
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = "tst.pdf";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};

[#53584] Wednesday, August 29, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ammonderekm

Total Points: 247
Total Questions: 105
Total Answers: 98

Location: Tuvalu
Member since Sat, Feb 11, 2023
1 Year ago
;