Reputation: 31
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?
Upvotes: 1
Views: 5963
Reputation: 3215
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.
Upvotes: 0
Reputation: 1108632
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.
Upvotes: 1
Reputation: 4763
you can use output stream as follows after setting contentType
Printwritter out =response.getWritter();
out.println(imageObject);
out.flush
Upvotes: 0