How can I return binary image data from an abortable AJAX request and set the result to the src of an HTML/DOM image? How can I return binary image data from an abortable AJAX request and set the result to the src of an HTML/DOM image? ajax ajax

How can I return binary image data from an abortable AJAX request and set the result to the src of an HTML/DOM image?


You would have to base64-encode the data into a data: URI to achieve that. But it wouldn't work in IE6-7, and there are limitations on how much data you can put in there, especially on IE8. It might be worth doing as an optimisation for browsers where it's supported, but I wouldn't rely on it.

Another possible approach is to use the XMLHttpRequest to preload the image, then just discard the response and set the src of a new Image to point to the same address. The image should be loaded from the browser's cache. However, in the case where you're generating the images dynamically you would need to pay some attention to your caching headers to ensure the response is cachable.


Try e.g.

this.src="data:image/png;base64,XXX"

...where XXX is your binary data, base64-encoded. Adjust the content-type if necessary. I wouldn't be optimistic about wide browser support for this, though.


You should be able to use data URIs, similar to the solution I identified in an earlier question. Note that this will not work with older browsers.