Question

Inserting and Retrieving image to and from MySQL

Asked by: widiyanto

Hi,

I would like to know how to insert and retrieve image to and from mysql. I've read the javazoom.net the uploadbean but still not sure how to do it. Is there anyone who knows how to do it? Is there any sample code or links to do that? Thanks...

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-10-26 at 02:25:03ID21182627
Tags

mysql

Topic

Java Server Pages (JSP)

Participating Experts
3
Points
100
Comments
29

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. PICUTRES MYSQL HOW TO STORE AND RETRIEVE THEM
    I have been going nuts trying to find a simple way to store pictures in mysql and retrieve them with php and a html form. Can anyone write the mysql part on how I insert them in mysql using the mysql monitor. Then how I would retrieve them using a php script and a html form .

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: TimYatesPosted on 2004-10-26 at 02:28:50ID: 12408905

I would upload the image (uning an upload bean like the javazoom one, the jakarta FileUpload library, or the OReilly upload servlet), then:

1) create a temp filename for your uploaded images directory inside the web application (using File.createTempFile)
2) Save the image to this temp filename
3) store this temp filename, and the original filename in the mySQL database (as 2 strings fields)

You can then display the image inside normal <IMG tags (rather than having to extract them from the database, and streaming them to the browser using a servlet)

And the database will be smaller

Tim

 

by: widiyantoPosted on 2004-10-26 at 02:40:52ID: 12408977

Yah, At first I also think like that but my supervisor want the image to be inserted to Mysql...
I tried the javazoom but I always have error which says it can not find the uploadbean class but I already paste the jar file to the classpath. but I haven't try the fileupload library and OReilly upload servlet.. any ideas how to solve this?

 

by: TimYatesPosted on 2004-10-26 at 02:59:38ID: 12409083

>  but I already paste the jar file to the classpath.

Put the jar into

WEB-INF/lib

of your web application :-)

http://www.jguru.com/forums/view.jsp?EID=720163

Shows you how to insert the image into MySQL....  

But it has to be said, that it just makes things tricky for no (apparent) reason ;-)  

But the supervisor is always right :-D

 

by: TimYatesPosted on 2004-10-26 at 03:02:05ID: 12409091

BTW:  Just incase you get no joy from the javazoom upload bean, even after putting the jar in the right place;

The Jakarta Fileupload bean is here:  http://jakarta.apache.org/commons/fileupload/
and the COS servlet (OReilly) is here:  http://www.servlets.com/cos/
Though the licence for the COS one says that you have to buy the book if you use it commercially :-)

Both come with examples :-)

Tim

 

by: krishnaashuPosted on 2004-10-26 at 04:46:34ID: 12409704

Here's my test database for storing images (sorry for the column line-up!):
mysql> use test;
Database changed
mysql> describe blobber;
+--------+---------+------+-----+---------+----------------+
¦ Field ¦ Type ¦ Null ¦ Key ¦ Default ¦ Extra ¦
+--------+---------+------+-----+---------+----------------+
¦ id ¦ int(11) ¦ ¦ PRI ¦ NULL ¦ auto_increment ¦
¦ picbox ¦ blob ¦ YES ¦ ¦ NULL ¦ ¦
¦ info ¦ text ¦ YES ¦ ¦ NULL ¦ ¦
+--------+---------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
You can store pictures in one of two ways: as a path to the file, as suggested, or as a text string in a text or blob mysql field.

In my test table, I store the string version of the picture in the "picbox" field, and the path to the actual image file in the "info" field.

Here's a small piece of what it looks like in the database:

select * from blobber limit 1;
+----+------------------+-------------+
¦ id ¦ picbox ¦ info ¦
+----+------------------+-------------+
¦ 1 ¦ Gif89ai?D?x^.etc.¦ /image.gif ¦
+----+------------------+-------------+
There can be a lot of data in "picbox", depending on how big the picture file is.

I use PHP to send the instructions to "LOAD_FILE('/image.gif')" to put the picture data into "picbox", but you can do it from a terminal or (probably) using one of the graphical mysql managers.

Try just storing and using the path to the image file while you learn, Butterfly_Wing. If you use the "picbox" method of storing the picture file data, you need to do a bunch of other stuff to your PHP installation to get it to work.

<font color=red>LOAD_FILE will serve the purpose</font>
 
regards

Ashu Krishna

 

by: TimYatesPosted on 2004-10-26 at 04:57:22ID: 12409768

This is JSP, not PHP tho ;-)

 

by: rrz@871311Posted on 2004-10-26 at 07:05:15ID: 12410938

 

by: TimYatesPosted on 2004-10-26 at 07:15:58ID: 12411069

As someone who's had to try and reclaim BLOB, CLOB, and ordinary data out of an Oracle database after it got too big, and fell over in a bad way (losing timestamp on the transaction logs, and all manner of horribleness), I disagree with his first three paragraphs ;-)

It's a good article tho ;-)

 

by: widiyantoPosted on 2004-10-26 at 18:22:42ID: 12417488

haha... ok... I'll go and try later.. now my supervisor ask me to do something else first.. as you say supervisor always right... :P

 

by: krishnaashuPosted on 2004-10-26 at 20:43:44ID: 12418302

I know that probel is related to JSP but te funda is same you can try fileupload in insertinto command
:)

 

by: widiyantoPosted on 2004-10-26 at 21:13:04ID: 12418459

Hi,

I'm trying the code on http://www.jguru.com/forums/view.jsp?EID=720163 but it always give me this error:

image_path:bear.jpg error:bear.jpg (No such file or directory)

Do we need to give the full path of the image file or just the image name?
I'm using 2 jsp file to do this, 1 is addSample1.jsp, 2 is sample_action1.jsp. Can you help me? Thanks

in the addSample1.jsp:
 <tr>
      <td width="25%"><font face="Arial, Helvetica, sans-serif" size="-1">Image Path </font></td>
      <td><input name="image_path" type="FILE" size="75"></td>
    </tr>

in the sample_action1.jsp:

String imagepath = request.getParameter("image_path");
out.println("image_path:"+ imagepath);
sql = "insert into sampledefinition (sample,description,sketch,createdBy,createdOn) values (?,?,?,?)";
    try
    {
          pstmt = con.prepareStatement(sql);
          pstmt.setString(1,sample);
          pstmt.setString(2,description);
          File imageFile = new File(imagepath);
          InputStream is = new FileInputStream(imageFile);
          pstmt.setBinaryStream( 3, is, (int)(imageFile.length()));
          pstmt.setString(4,userId);
          pstmt.setString(5,currentdate);
          retVal = pstmt.executeUpdate();
          stmt.close();
          response.sendRedirect("sample1.jsp");
       } catch(Exception e)
       {
          out.println("error:" + e.getMessage());
        }
            

 

by: krishnaashuPosted on 2004-10-26 at 21:46:31ID: 12418568

try to give complete path(i.e. absolute or relative)

 

by: widiyantoPosted on 2004-10-26 at 23:06:14ID: 12418809

Yah.. I also tried to give the full path like:

String imagepath = "C://Documents and Settings//Administrator.TECH01//My Documents//My Pictures//bear.jpg";

but still have error:
image_path:C://Documents and Settings//Administrator.TECH01//My Documents//My Pictures//bear.jpg error:C:/Documents and Settings/Administrator.TECH01/My Documents/My Pictures/bear.jpg (No such file or directory)

most likely is that I can not get the file path from the input.... Is it correct wat I've done?

 

by: TimYatesPosted on 2004-10-27 at 00:18:04ID: 12419083

> Is it correct wat I've done?

No, the full filename is the name on the client's computer, not yours...  

What you need to do is call:

pstmt.setBinaryStream( 3, file.getInputStream(), sz ) ;

where "file.getInputStream()" is the inputstream for the multipart file being uploaded -- and sz is the size of it...

 

by: widiyantoPosted on 2004-10-27 at 00:38:04ID: 12419157

Hi Tim,

Is it like this?

File imageFile = new File(imagepath);
InputStream is = new FileInputStream(imageFile);
pstmt.setBinaryStream( 3, is, (int)(imageFile.length()));

But I also can not pass the parameters from 1 jsp page to another. It always return null.... I guess it's because the:
<form name="form1"  method="post" ENCTYPE='multipart/form-data' action="sample_action1.jsp?cmd=add">

do you know the solution?

 

by: TimYatesPosted on 2004-10-27 at 00:45:55ID: 12419197

Hmmm...  I have had a look at that javazoom upload bean (I've never used that one before), and I can't see how you can do it this way (the documentation seems to rely on jsptags to do all the processing)...

Basically...  if the image is getting saved to a directory on the server, then yes, your way is correct

What you should be able to do, it get back a list of "multipart-parts" from the bean.  you can then go through this list and call "getParameter" on each of them...  What you will find generally is that there are 2 parts...  one contains all your parameters, the other contains the file.

If the image is not getting saved on the server, then you should be able to get an inputstream for this file (in the respective part), and just pass that straight to the setBinaryStream call...

I hope this is a bit clearer...

> But I also can not pass the parameters from 1 jsp page to another. It always return null.... I guess it's because the:

Yeah, that's why...  you have to iterate through the parts, and call getParameter on each part to see if that parameter is there...

 

by: widiyantoPosted on 2004-10-27 at 00:53:49ID: 12419235

Sorry... but I still don't understand wat you're trying to say...hehe....

> Basically...  if the image is getting saved to a directory on the server, then yes, your way is correct

but my supervisor wants the image to be inserted to mysql which mean I can not use this method is it?

 

by: TimYatesPosted on 2004-10-27 at 01:00:53ID: 12419273

But you are trying to do:

> File imageFile = new File(imagepath);
> InputStream is = new FileInputStream(imageFile);

The "imagePath" that you have, is the path of the image ont the client machine, wheras this code is being run on the server machine, so this will always fail...

Can you actually iterate through the parts using the javazoom upload bean?  Then getInputStream on the file object?

 

by: widiyantoPosted on 2004-10-27 at 01:48:40ID: 12419504

ok.. I try first...

 

by: widiyantoPosted on 2004-10-27 at 19:32:43ID: 12429799

hi Tim,

I can run the databaseupload in the javazoom sample code. but I am not sure how to insert it in my program. Do you know how the databaseupload know which table that they want to insert? Sorry, I am a bit blur in this...

here is the part of my program:

String sample = request.getParameter("sample");
String description = request.getParameter("description");

try
 {
if (MultipartFormDataRequest.isMultipartFormData(request))
{
 MultipartFormDataRequest mrequest = new MultipartFormDataRequest(request);
 String todo = null;
 if (mrequest != null) todo = mrequest.getParameter("todo");
 if ( (todo != null) && (todo.equalsIgnoreCase("upload")) )
 {
     Hashtable files = mrequest.getFiles();
     if ( (files != null) && (!files.isEmpty()) )
     {
        UploadFile file = (UploadFile) files.get("image_path");            
        if (file != null) out.println("<li>Form field : uploadfile"+"<BR> Uploaded       file : "+file.getFileName()+" ("+file.getFileSize()+" bytes)"+"<BR> Content Type : "+file.getContentType());
        sql = "insert into sampledefinition (sample,description,sketch,filename,createdBy,createdOn) values (?,?,?,?,?)";
        pstmt = con.prepareStatement(sql);
        pstmt.setString(1,sample);
        pstmt.setString(2,description);
        pstmt.setBinaryStream(3, upBean.store(mrequest, "image_path"));
        pstmt.setString(4,file.getFileName());
        pstmt.setString(5,userId);
        pstmt.setString(6,currentdate);
        retVal = pstmt.executeUpdate();
        pstmt.close();
        response.sendRedirect("sample1.jsp");
     }else
     {
         out.println("<li>No uploaded files");
     }
}
else out.println("<BR> todo="+todo);
}
}catch (Exception e)
{
e.printStackTrace();
}      
                        

 

by: widiyantoPosted on 2004-10-27 at 23:31:31ID: 12430810

Hey Tim, I think I know what you're trying to say..
IS it like we try to get the parameter by using MultipartFormDataRequest then insert to the mysql something like this? :D but i still got error : "todo:upload sampleikad description:test uploadfile:null error:null"

<tr>
      <td><font face="Arial, Helvetica, sans-serif" size="-1">Sample Type</font></td>
      <td><input name="sample" type="text" size="50" maxlength="50">
      </td>
    </tr>
    <tr>
      <td width="25%"><font face="Arial, Helvetica, sans-serif" size="-1">Description </font></td>
      <td>
        <input type="text" name="description" maxlength="50" size="50">
      </td>
    </tr>
      <tr>
      <td width="25%"><font face="Arial, Helvetica, sans-serif" size="-1">Image Path </font></td>
      <td> <input name="uploadfile" type="FILE" size="50"></td>
    </tr>
    <tr>
      <td>
        <div align="center">&nbsp; </div>
      </td>
      <td>
        <input type="reset" name="RESET" value="Reset">
            <input type="hidden" name="todo" value="upload">
            <input name="addcode" type="submit" id="add" value="Add Code">
      </td>
</tr>

MultipartFormDataRequest mrequest = new MultipartFormDataRequest(request);
String todo = mrequest.getParameter("todo");
String sample = mrequest.getParameter("sample");
String uploadfile = mrequest.getParameter("uploadfile");
String description = mrequest.getParameter("description");
Hashtable files = mrequest.getFiles();
UploadFile file = (UploadFile) files.get("uploadfile");
sql = "insert into sampledefinition (sample,description,sketch,filename,createdBy,createdOn) values (?,?,?,?,?,?)";
pstmt = con.prepareStatement(sql);
pstmt.setString(1,sample);
pstmt.setString(2,description);
File imgFile = new File(file.getFileName());
pstmt.setBinaryStream(3, new FileInputStream(file.getFileName()),(int)imgFile.length());
pstmt.setString(4,file.getFileName());
pstmt.setString(5,userId);
pstmt.setString(6,currentdate);
retVal = pstmt.executeUpdate();

 

by: widiyantoPosted on 2004-10-27 at 23:54:44ID: 12430930

Hi Tim,

Finally, I've managed to do this... I just change the:

pstmt.setBinaryStream(3, new FileInputStream(file.getFileName()),(int)imgFile.length());

to:
pstmt.setBinaryStream(3, file.getInpuStream(),(int)file.getFileSize());

but I can not get the userId and direct to another page though... can help me? cos the userId is retrieved by using session..

String userId = (String)session.getValue("userid");
response.sendRedirect("sample1.jsp");

 

by: TimYatesPosted on 2004-10-28 at 00:33:27ID: 12431086

Should be:

String userId = (String)session.getAttribute("userid");

 

by: widiyantoPosted on 2004-10-28 at 02:53:58ID: 12431789

OK, One last question... how to retreive from database and display it on the HTML? :D

I use:

byte[] b = rs.getBytes(4);
<td><img src="sampleView.jsp?sampleId=<%=sampleId%>" width="84" height="110"></td>

but it doesn't work.. hehe...

 

by: TimYatesPosted on 2004-10-28 at 02:59:37ID: 12431820

You will have to write a servlet, that writes the bytes from the database to the response object...

something like:

response.setContentType( "image/gif" ) ;
byte[] b = rs.getBytes(4);
response.getOutputStream().write( b ) ;

But it will have to be another jsp or servlet...  then you can do:

<img src="sampleView.jsp?sampleId=<%=sampleId%>" width="84" height="110">

assuming "sampleView.jsp" is the thing that does what I put above ;-)

 

by: widiyantoPosted on 2004-10-28 at 19:48:54ID: 12440899

ok.. thanks.. 1 more last question.. hehe..

when I try in my server, there is this error that says "IllegalStateException getOutputStream() has already been called for this response" then I try to put out.flush before or after response.getOutputStream().write( b ) ; but in the end I can not display my picture...

 

by: TimYatesPosted on 2004-10-28 at 23:42:10ID: 12441793

Hmmm....  can you post your code?

Hee hee, what a lot of questions for 100 points ;-)

Tim

 

by: widiyantoPosted on 2004-10-29 at 00:13:49ID: 12441918

haha... it's ok.. I've solved it already.. thanks..

 

by: TimYatesPosted on 2004-10-29 at 00:40:23ID: 12442027

Hehehe cool :-)

Good luck with it!

Heh, next time I shall try to get an "A" grade :-/  ;-)

Tim

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...