edwardsmarkf edwardsmarkf - 9 months ago 262
Javascript Question

Using jquery ajax to download a binary file

I am attempting to use jquery ajax to download a binary audio file.

Normally i would just issue a command like this:

windows.location.href = 'http://marksdomain(dot)com/audioFile.wav' ;

However, recently our server has been waiting too long to respond, and I get a nasty gateway timeout message.

It has been suggested that i use jquery-ajax instead, which makes sense since then i would have more control over the timeout.

Here is the code i have played with so far:

{ url: 'http://marksdomain(dot)com/audioFile.wav'
, timeout: 999999
, dataType: 'binary'
, processData: false // this one does not seem to do anything ?
, success: function(result) {
, error: function(result, errStatus, errorMessage){
console.log(errStatus + ' -- ' + errorMessage);

When i omit the "dataType", the binary file is coming through about three times larger than it actually is on the server. However, when i make the dataType equal to "binary", ajax throws an error:

"No conversion from text to binary"

From some earlier posts, it sounds as if jquery-ajax cannot handle binary files in this manner.

I did discover Delivery.js which actually works quite well for what I am attempting, but I would rather not use a node solution if possible.

Any suggestions?


Just use XHR directly. This example is taken from MDN:

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

oReq.onload = function(oEvent) {
  var arrayBuffer = oReq.response;

  // if you want to access the bytes:
  var byteArray = new Uint8Array(arrayBuffer);
  // ...

  // If you want to use the image in your DOM:
  var blob = new Blob(arrayBuffer, {type: "image/png"});
  var url = URL.createObjectURL(blob);
  someImageElement.src = url;

  // whatever...