• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Fetching image from database

 
Boon Subra
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I am trying to fetch an image from the database and display it in a JSP page. The byte output is printing. Please help to convet the value and display it in the browser.
The code is as follows.
if(rs.next())
{
BufferedInputStream bins = new BufferedInputStream(rs.getBinaryStream(1));
byte[] buf = new byte[4*1024];
int len;
while((len= bins.read(buf,0,buf.length))!=-1)
{
out.write(buf,0,len); // the output is getting printed here.
}
How to display it in the browser.
Thanks,
Bhuvana
 
Nicholas Cheung
Ranch Hand
Posts: 4982
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After you read the image to the JSP, I think you need to write it to the file system, that can be accessed by public.

Does this what you need?
Nick.
[ March 11, 2004: Message edited by: Nicholas Cheung ]
[ March 11, 2004: Message edited by: Nicholas Cheung ]
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65124
92
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no need to write the image to a file. Your best bet would be to code up a servlet that retrieves the image bytes from the DB and returns them as the response, with the appropriate content type and lengths specified.
Then in your JSP you would use an img tag just like any other image, setting the src attribute to the URL of the servlet.
[ March 14, 2004: Message edited by: Bear Bibeault ]
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you're doing is attempting to mix text and binary output in a single servlet response.
This is impossible. The content type is set only once (any new set would override that) and sent to the client in the HTTP headers.
Therefore your image is sent as a byte stream which the browser will attempt to interpret as HTML or clear text and dump to the screen.
Do as Bear said and code it as a servlet that sets the contenttype to jpeg (or whatever image format you use) and call that from an img tag in your JSP.
 
Boon Subra
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Bear and Jeroen,
Thanks a lot for the suggestion could you send how exactly I should write in the JSP page by setting the context type.
Thanks
Bhuvana
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65124
92
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry that should have been content type.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic