35

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;
xhr.open("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;
        ret.push(String.fromCharCode(byte));
    }
    var data = ret.join('');
    data = "data:application/pdf;base64," + btoa(data);

    window.open(data, '_blank', 'resizable, width=1020,height=600');
}, false);

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

Thanks!

7
  • 1
    What does it mean "show"? Commented Jul 17, 2013 at 9:50
  • you should check this answer: stackoverflow.com/questions/9620497/… Commented Jul 17, 2013 at 9:51
  • Do you want to download images only? Like pngs and jpegs? Commented Jul 17, 2013 at 9:56
  • @Tommi - 'Show' is the possibility to download the file Commented Jul 17, 2013 at 9:58
  • @JoDavid - No. I want to download any type of document. Images(png, jpeg, gif), documents (pdf, doc, txt), ... Commented Jul 17, 2013 at 9:59

1 Answer 1

68

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();
xhr.open("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);
        window.open(objectUrl);
    }
};
xhr.send();

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();
xhr.open("GET", requestUrl);
xhr.responseType = "blob";

xhr.onload = function () {
    onDownloaded(this);
};
xhr.send();

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() {
    onImageDownloaded(img);
}

// start the download by setting the src property
img.src = requestUrl
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for the answer. But my problem is a bit different. I can download pdfs or images, but when i call the REST service that returns the binary data, i don't know what is the type of the file.
You could make another request just before downloading the file to get the fileType and maybe the file name (for the UI).
why would you not use content-type header instead of hard coding type as application/pdf?
A tiny correction Jo, for a bytearray Brob parameter should be an array. ...new Blob([xhr.response], {type: 'application/pdf'});
Where the function onDownloaded is defined?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.