MOCKSTACKS
EN
Questions And Answers

More Tutorials




Write byte array to file in Javascript


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

Output


Example 2


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


Conclusion

In this page (written and validated by ) you learned about Write byte array to file in Javascript . What's Next? If you are interested in completing Javascript tutorial, we encourage you simply to start here: Javascript Tutorial.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.