Ajax Binary Response

Viewed 21895

Hi I'm wondering if there's anyway to stream a binary response in AJAX? This would be an ultimate solution otherwise I would need to realize the binary image to a file then stream that file to the user with a different URL.

new Ajax.Request('/viewImage?id=123', {
  // request returns a binary image inputstream
  onSuccess: function(transport) {
      // text example
      // alert(transport.responseText)

      // QUESTION: is there a streaming binary response?
      $('imgElem').src = transport.responseBinary;
  },
  onFailure: function(transport) {
      // handle failure
  }
});
6 Answers

When you call your service, you should ask for a dataType: 'binary' response. Then, you can use saveAs(FileSaver.js) to trigger the download or createObjectURL to open in new window.

But, $.ajax doesn't let you download binary content out of the box, it will try to decode your binary from UTF-8 and corrupt it. Either use a jQuery plugin to solve this problem jquery.binarytransport.js

exemplo:

$.ajax({
    type: "POST",
    url: $("form#data").attr("action"),
    data: formData,
    dataType: 'binary',     //--> using jquery.binarytransport.js
    success: function (response) {
        // Default response type is blob
        
        saveAs(response, "test.pdf"); //--> using FileSaver.js

        let fileURL = URL.createObjectURL(blob);
        window.open(fileURL);        // open file in new window
    }
});

Good look! :)

I managed to get download of binary file without corrupted data working using jQuery ajax by adding:

xhrFields: {responseType: 'blob'}

Related