Javascript:Display an image downloaded with XMLHTTPRequest (us)
This small javascript code will display an image downloaded with XMLHttpRequest. This make available the response HTTP headers and metadatas included in the image file.
Thanks to the XMLHttpRequest download, the following are available:
- HTTP headers received with the image
- binaries datas of the image file
The code to execute a binary download with XMLHttpRequest is fairly easy to find on the Internet:
//---------------------------------------- var xhr = getXMLHttpRequest(); xhr.onreadystatechange=ProcessResponse; xhr.open("GET",url, true); xhr.overrideMimeType('text/plain; charset=x-user-defined'); xhr.send(null);
Characters found in ”xhr.responseText” are not BYTES but WORDS (two bytes) with the hi-byte set with a random like value which need to be cleared. It’s the purpose of “& 0xff” in the script below. However, in the script object of this page, the fix is included “encode64″ function:
//-------------------------------- function ProcessResponse() { if(xhr.readyState==4) { if (xhr.status==200) { retval =""; for (var i=0; i<=xhr.responseText.length-1; i++) retval += String.fromCharCode(xhr.responseText.charCodeAt(i) & 0xff); } }h
The image is displayed by applying the binaries datas, base64 encodeded, to image.src:
//----------------------------------------
var img=document.getElementById("myimg"); img.src="data:image/jpeg;base64," + encode64(xhr.responseText); img.style.display="";
Done.
script complet: jsxhrimg.zip
Bon post.
Commentaire par Etienne — 1 juillet 2010 @ 20:11