Consultant Informatique Réseau et Internet

15 janvier 2010

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.

French version

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

Un commentaire

  1. Bon post.

    Commentaire par Etienne — 1 juillet 2010 @ 20:11

Flux RSS des commentaires de cet article.

Désolé, les commentaires sont fermés pour le moment.

Propulsé par WordPress