Ajax (XHR) download binary content as Blob

Using XMLHTTPRequest (ajax) transporting data between client and server has been popular for a while. Sometimes, we want our browser to retrieve binary data from server (as ArrayBuffer or Blob) such as pdf, image, and psd files. This post will go through how to achieve it with XMLHTTPRequest and jQuery.

XMLHTTPRequest

For XMLHTTPRequest, just simply setup the responseType of XHR instance to either arraybuffer or blob. Example:

1
2
3
4
5
6
7
8
9
10
11
var xhr=new XMLHTTPRequest();
xhr.open("GET", url, true);
//Now set response type
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load',function(){
if (xhr.status === 200){
console.log(xhr.response) // ArrayBuffer
console.log(new Blob([xhr.response])) // Blob
}
})
xhr.send();

jQuery Ajax with arraybuffer or blob

$.ajax does not support either arraybuffer or blob as its dataType. Thus we need write a beforeSend handler:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//setup ajax
$.ajaxSetup({
beforeSend:function(jqXHR,settings){
if (settings.dataType === 'binary'){
settings.xhr().responseType='arraybuffer';
settings.processData=false;
}
}
})
//use ajax now
$.ajax({
url:url,
dataType:"binary",
success:function(data){
console.log(data); //ArrayBuffer
console.log(new Blob([data])) // Blob
}
})

For more information about responseType, take a look at this.