how to display image using servlets..???
2 posts in topic
Flat View  Flat View

Posted By:   man_ju
Posted On:   Friday, August 9, 2002 01:45 AM


can any body please give me the code for
putting an image into database and retriving
it through jdbc using servlets and display that
image on to the browser.

iam using an html to send imagename and
using servlet to save it to database
and again want to retrive it through servlet
and display it on the browser.


Re: how to display image using servlets..???

Posted By:   John_Mendes  
Posted On:   Tuesday, August 13, 2002 08:44 AM

What are you using to save the images into the database? a file upload? or are you dynamically generating the image on the server then storing into the db?

The following puts the image into a db (untested):

//assume that there is an byte array representation of the image in image[]

//setup the driver and get the connection/preparedstatement
Connection connection = DriverManager.getConnection("the connection url for this driver (see the docs for it)");
PreparedStatement prepared = connection.prepareStatement("INSERT INTO MyTable (Image) VALUES (?)");

//store the image into the blob
Blob blob = new Blob();
BufferedOutputStream out = new BufferedOutputStream(blob.setBinaryStream(0));
//should use buffering...
while (int i = 0; i < image.size; i++)

//now save the blob to the db
prepared.setBlob(1, blob);

//close everything
catch (Exception e)
//really generic exception handling

Even though I think this will work, I can't promise it will (since I did it from the top of my head) but I hope that it points you in the right direction.


Re: how to display image using servlets..???

Posted By:   James_Bayer  
Posted On:   Friday, August 9, 2002 06:53 AM

change the mime type of the response to the appropriate image...

httpResponse.setContentType( "image/gif" );


httpResponse.setContentType( "image/jpeg" );


then get the bytes from the db, and write them out to the response output stream. that's it. note that you'll need more than one servlet/jsp to create a webpage using this method. i.e. you can't but html text and ninary images in the exact same response. so use one servlet to generate the html, which has an tag which calls your image servlet.
About | Sitemap | Contact