views:

259

answers:

2

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
  }
});
A: 

You can send any response you want, being it plain text, HTML, an image... whatever! It's up to you how to handle it when you receive it.

But... you cannot assign a binary image to the <IMG> src attribute. You'd better just return the URL to the image and assign that instead - well, to be honest, there are some encodings to embed images in the SRC, but they are not cross-browser so you'll want to stay away from them.

Seb
+3  A: 

What you can do, if you are trying to generate an image on the fly, is to just do:

<img src="http://myurl/myfile.php?id=3" />

then you can send the data with the appropriate mimetype.

If you really want to send an image, then you may want to look at the HTML5 canvas tag, but I am not certain how excanvas would work with this, for being cross-platform.

You could write to the canvas, but it would be more efficient to just use the img tag.

James Black