Tech163 Tech163 - 1 year ago 138
jQuery Question

jQuery Ajax - downloading incomplete (binary) file

This is what I have:


url: "",
dataType: "text",
data: "",
success: function(data) {
error: function(a, b, c) {}

When I run that locally (in Safari 6.0.5 on OS X), I get 211300. However, the actual file appears to be 218882 bytes. With something fully ASCII (such as, it seems to work correctly.

I don't need to download the file, but rather, work with its content.

Is there any way to make ajax work with binary files (either client side or server side) without resorting to using base64?

Answer Source

I think you need to use typed arrays. Javascript way of dealing with binary. There is no other way to deal with pure binary data. But with typed arrays you can do almost everything that you would want to do with binary anywhere else.

Sending Typed Array using Ajax

var myArray = new ArrayBuffer(512);
var longInt8View = new Uint8Array(myArray);

for (var i=0; i< longInt8View.length; i++) {
  longInt8View[i] = i % 255;

var xhr = new XMLHttpRequest;"POST", url, false);

Receiving Typed Array

2 ways to do it...First

var oReq = new XMLHttpRequest();"GET", "/myfile.png", true);
oReq.responseType = "arraybuffer";

oReq.onload = function (oEvent) {
  var arrayBuffer = oReq.response; // Note: not oReq.responseText
  if (arrayBuffer) {
    var byteArray = new Uint8Array(arrayBuffer);
    for (var i = 0; i < byteArray.byteLength; i++) {
      // do something with each byte in the array



var oReq = new XMLHttpRequest();"GET", "/myfile.png", true);
oReq.responseType = "arraybuffer";

oReq.onload = function(oEvent) {
  var blob = new Blob([oReq.response], {type: "image/png"});
  // ...



Using Jquery

Sending: $.ajax(url,{data:myArray});

Receiving: not tested...

    contentType: "arraybuffer",
    success: function(d){
        var blob = new Blob([d], {type: "image/png"}),
            u = URL.createObjectURL(blob);