Search code examples
javascriptarraysrestdownloadxmlhttprequest

Write Byte Array to a file JavaScript


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 image description here


Solution

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