Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Hibernate, BLOB(image): Retrieving images from DB(MySQL)

  Asked By: Darla    Date: Nov 09    Category: Java    Views: 9387

I'm developing a web app using Struts 1.2, Hibernate 3.0 and MySQL 5 and I can properly upload images into the DB, but the problem is that I do not know how to restore them and display them bak on a web page.
I've tried some code like this in my UploadFileAction class:

// Get the image Blob from the database
Blob blob = rs.getBlob( 1 );
InputStream in = blob.getBinaryStream();

// Output the blob to the HttpServletResponse
res.setContentType( "image/jpeg" );
BufferedOutputStream out = new BufferedOutputStream( res.getOutputStream() );
byte by[] = new byte[ 32768 ];
int index = in.read( by, 0, 32768 );
while ( index != -1 )
out.write( by, 0, index );
index = in.read( by, 0, 32768 );



2 Answers Found

Answer #1    Answered By: Taylor White     Answered On: Nov 09

you could save filename in db and then save filecontent in specific repository(folder) in root,
it means that you could save the name of your file into DB only.
and upload  file in the folder that you specify in the root for images,
when you wanna use it you should retrieve file name frim DB and image  url is static from your root folder. like this jsp sample :
<img src="/images/<%= rs("ImagesField")%>" border="0"/>

if you don't wanna do like this you could save content of your image in DB that is not recomanded, you should get binary of your file and then input to DB.
attention to your code  more.

Answer #2    Answered By: Cay Nguyen     Answered On: Nov 09

Many thanks for your reply. but as I believe the first way would be better, then I'd still choose storing them in DB.

Didn't find what you were looking for? Find more on Hibernate, BLOB(image): Retrieving images from DB(MySQL) Or get search suggestion and latest updates.