Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically generated images, fetched using POST

I need to dynamically load images inside a JSP. I've tried the <img src="servletUrl?p1=x&p2=y"/>, but the problem is that the URL is too long to be sent using GET.

I'm now performing a POST call. From the servlet I'm generating a pie chart image, based on the params I send. The image is not persisted, so I can't return something like "images/image1.jpg" and set that as src of the image.

So I'm returning the image as a byte array and setting the appropriate image content type.

My question is: once I have the image bytes in javascript, how do I display them in the corresponding img tag?

This is my AJAX call:

new Ajax.Request(url, {
        method: 'post',
        parameters: params,
        onComplete: function(request) {
                    alert(request.responseText);      
        }
});
like image 359
madalina Avatar asked Nov 03 '22 23:11

madalina


1 Answers

I haven't try this my self but it should work. You could create an image and set its src using a dataUrl. You will have to convert the byte[] in to a base64 encoded string for this to work.

new Ajax.Request(url, {
        method: 'post',
        parameters: params,
        onComplete: function(response) {
            var img = new Image();
            img.src = "data:image/png;base64," + response;

            document.body.appendChild(img);
        }
});
like image 117
Andreas Avatar answered Nov 11 '22 02:11

Andreas