Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling images from XMLHttpRequest (with HTML and Javascript)

I am using an XMLHttpRequest to fetch an image from a server (run locally from a third party server-applet)

A simplified version of the code is shown below.

The image is returned as a JPEG and the returned header shows "content-type= image/jpg". I can view the information via Firebug for Firefox.

However I am having a terrible time being able to show the actual image on a webpage because it is the image data being returned from the server NOT a uri to the image location.

What is the proper way to display this image from the returned data? Should I be using a <span> tag or an <img> tag or a <magical-show-image-from-data> tag?

function getXML(url, postData, requestStateChangeHandler){        
    if(window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {//Code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = requestStateChangeHandler;

    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader('Content-Type', 'text/xml');
    xmlhttp.setRequestHeader('Cache-Control', 'no-cache');
    xmlhttp.send(postData);
}


function requestStateChangeHandler(){
    if (xmlhttp.readyState == 4) 
    {
        if(xmlhttp.status == 200)
        {
            document.getElementById('results').innerHTML = xmlhttp.responseText;
        }
        else
            dump("Error loading page\n");
    }
}
like image 675
Toymakerii Avatar asked Sep 15 '10 21:09

Toymakerii


Video Answer


1 Answers

You can use inline images

on server side encode your response in base64

in php use base64_encode("your data")
and in javascript

result = document.getElementById('results');
result.innerHTML = '<img src="data:image/gif;base64,' + xmlhttp.responseText + '"/>';
like image 59
jcubic Avatar answered Nov 14 '22 23:11

jcubic