1

I am uploading an image file from database to jsp. I've selected image using SQL as below

select (logo_img_one) from accounts_logo where logo_usrm_id=1

I read the image using binarystream as

InputStream readImg = rs1.getBinaryStream(1);

and made content type as "image/jpeg" as

response.setContentType("image/jpg");

Now I want to know how to use getoutputstream of response to send the image to ajax and how to get in ajax. How can I achieve this?

3 Answers 3

1

This is not going to work. JavaScript can't save the retrieved bytes locally or something and tell the browser to display it. Best what you can do is to pass an URL to the image back as a string and let JavaScript set it as the src attribute of a HTML <img> element.

E.g. in servlet

response.setContentType("text/plain");
response.getWriter().write(imageUrl); // e.g. "images/some.png"

and in JS

var imageUrl = xhr.responseText;
var img = document.createElement("img");
img.src = imageUrl;
document.getElementById("someDivId").appendChild(img);

This way a

<div id="someDivId"></div>

will dynamically end up in something like

<div id="someDivId><img src="images/some.png" /></div>

You can create an image servlet which streams the image from the DB to the outputstream of the response and map the servlet on /images/*. You can find an example here.

Sign up to request clarification or add additional context in comments.

Comments

0

you can use output stream as follows after setting contentType

   Printwritter out =response.getWritter();
   out.println(imageObject);
   out.flush

4 Comments

Images are binary data, not character data. Treating binary data like character data would only corrupt binary data.
set your content type as response.setContentType("image/gif");
Mr.BalusC stop criticizing other nd just focused in ur business. Because in my answer, I hv no where mention its character object.
Yes, you did. You suggested to use Writer.
0

It might work... The idea is to set the src attribute of the image to something like:

src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAYlJREFUeNrMVD1rwlAUPfkwBBxFKQQlDhmjqzj4F9w7FfwThZaW9n8UnDrrn1BEXNTBRQQhEE1ERRR0Sd990A7VaKJJ6YHzEu4N99z3zrsRGo2GAuCF8YFRQzSwGOuM7zJb3hgfES2o0SdGSWRLDfGhRgLpGAXS4q0VCoUCBEHwzd8skM/nUSqVoCjKybz8O1CtVn2LeZ4H27YxnU6xXC6x3+95PJPJoFKpoN1uY7vdnhfww3w+x3A4xGaz4d3quo5sNvuTTyaTXKTb7cJ13csCzWbzKKaqKj/zXC4HSZKO8iRcLpcxGAwwmUzC7UDTNBSLRSQSiVAeyUGNpM4v4XA4oNfr8eMMLJBKpWCaJn9fLBawLAur1Qq73Y6b/H0pyNyrTDYMA7PZDKPRCOv1+uQ3ZCqZe9UcOI6DTqfjW5zMbLVa3Bu6RaE9GI/HZ/P9fp8/qfipYROj+ukEnuQgEx0GImKGHGSC//UO/kTAibG+QwIfMQrUyeRXusaM94x3ERW2GT8Zn78EGACRmoKUJhB1TQAAAABJRU5ErkJggg=="

the base64 string can be queried via ajax by calling your servlet and encode the input stream retrieved from DB.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.