nuno.filipesf nuno.filipesf - 1 year ago 103
Javascript Question

Download Binary Files with Javascript

I want to download binary files using Javascript.

I have a REST service that returns the binary data and i want to know if its possible to show the binary file, whichever the file extension.

This is my current code:

var xhr = new XMLHttpRequest;"GET", requestUrl);
xhr.addEventListener("load", function () {
var ret = [];
var len = this.responseText.length;
var byte;
for (var i = 0; i < len; i++) {
byte = (this.responseText.charCodeAt(i) & 0xFF) >>> 0;
var data = ret.join('');
data = "data:application/pdf;base64," + btoa(data);, '_blank', 'resizable, width=1020,height=600');
}, false);

xhr.setRequestHeader("Authorization", "Bearer " + client.accessToken);
xhr.overrideMimeType("octet-stream; charset=x-user-defined;");


Answer Source

Have a look at the MDN article on XMLHttpRequest.

If you set the response of the XMLHttpRequest to ArrayBuffer you could do the following:

var xhr = new XMLHttpRequest();"GET", requestUrl);
xhr.responseType = "arraybuffer";

xhr.onload = function () {
    if (this.status === 200) {
        var blob = new Blob([xhr.response], {type: "application/pdf"});
        var objectUrl = URL.createObjectURL(blob);;

Option 2:
You could use Blob as the response of the XMLHttpRequest. And then maybe save it in the FileSystem (FileSystem API)

It may look like:

var xhr = new XMLHttpRequest();"GET", requestUrl);
xhr.responseType = "blob";

xhr.onload = function () {

I've written a testcase for another stackoverflow question which works quite well: (Chrome only... at the time of writing this): (Feel free to look at the code)

Option 3:
If you only want to download and "show" images you can easily do this like so:

var img = new Image();

// add the onload event before setting the src
img.onload = function() {

// start the download by setting the src property
img.src = requestUrl