5
votes

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);      
        }
});
2
Why is the URL too long? That seems a bit odd... - beerbajay
hey, can you fiddle it out...that'd help - Parth Thakkar
@beerbajay: because one of the parameters is a JSONized document, with lots of fields. It's a document that is not yet persisted and based on the values the user inputs in the various fields a piechart is generated and returned from the servlet. - madalina
In which browsers should this be running? - Andreas
@Andreas: first place, in FF. But after I get it running in FF, I would also like to get it running in IE9 too. - madalina

2 Answers

2
votes

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);
        }
});
0
votes

Here's solution from top of my head, should work in all browsers:

Instead of AJAX and <img> tag, use an <iframe> pre-filled with form with hidden fields with all the necessary POST parameters and with onload handler set to submit this form to image serving script. Make this script return pure image that will be displayed in this iframe keeping rest of your page intact.