Using jquery ajax to download a binary file

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

Normally, I would simply issue this command:

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

However, recently our server has been waiting for a response too long, and I get an unpleasant message about the gateway timeout.

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

Here is the code I've played so far:

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

When I omit "dataType", the binary goes about three times as much as it actually does on the server. However, when I make dataType equal to binary, ajax throws an error:

 "No conversion from text to binary" 

From some early posts, it sounds like jquery-ajax cannot handle binary files this way.

I found Delivery.js that really works well enough for what I'm trying, but I would prefer not to use the node solution if possible.

Any suggestions?

+14
javascript jquery ajax
source share
3 answers

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... }; oReq.send(); 
+18
source share

You can configure the $ .ajax transport to change the settings, as indicated here: http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/

 // use this transport for "binary" data type $.ajaxTransport("+binary", function (options, originalOptions, jqXHR) { // check for conditions and support for blob / arraybuffer response type if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob))))) { return { // create new XMLHttpRequest send: function (headers, callback) { // setup all variables var xhr = new XMLHttpRequest(), url = options.url, type = options.type, async = options.async || true, // blob or arraybuffer. Default is blob dataType = options.responseType || "blob", data = options.data || null, username = options.username || null, password = options.password || null; xhr.addEventListener('load', function () { var data = {}; data[options.dataType] = xhr.response; // make callback and send data callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders()); }); xhr.open(type, url, async, username, password); // setup custom headers for (var i in headers) { xhr.setRequestHeader(i, headers[i]); } xhr.responseType = dataType; xhr.send(data); }, abort: function () { jqXHR.abort(); } }; } }); 

and then make your AJAX call:

  return $.ajax({ url: url, method: 'GET', dataType: 'binary', processData: 'false', responseType: 'arraybuffer', headers: { 'X-Requested-With': 'XMLHttpRequest' } }).then(function (response) { var data = new Uint8Array(response); //do something with the data return data; }, function (error) { alertify.error('There was an error! Error:' + error.name + ':' + error.status) }); 
+2
source share

If you must use jQuery, you can use $.ajaxSetup() to change the low level settings.

Example:

  // Set up AJAX settings for binary files: $.ajaxSetup({ beforeSend: function (jqXHR, settings) { if (settings.dataType === 'binary') { settings.xhr().responseType = 'arraybuffer'; } } }) // Make the actual call: let result = await $.ajax({ url: '/api/export/data', type: 'GET', contentType: 'application/json', dataType: 'binary', processData: false, headers: { token: localStorage.token, }, }); 
+1
source share

All Articles