Write Byte Array to a file Javascript

user1814595 picture user1814595 · Sep 2, 2018 · Viewed 9.2k times · Source

Hello Experts 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

Answer

Viney picture Viney · Sep 2, 2018

Since you are requesting a binary file you need to tell XHR about taht too 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 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);
};