i want to store the user uploaded image in database using Hibernate. But i am not sure how to do it.. Here is my code
JSP:
<form action="Image" method="post" enctype="multipart/form-data"> <br><br>
<table>
  <tr>
             <td>UserName:  </td>
             <td width='10px'></td>
             <td><input type="text" name="unname"/></td>
  </tr>
  <tr>
             <td>Upload: </td>
             <td width='10px'></td>
             <td><input type="file" name="filecover" value="Upload"/></td>
  </tr>
  <tr>
      <td><input type="submit" value="Submit" name="usubmit"></td>
  </tr>
</table>
</form>
DAO:
public void savePhoto1(String uname, Blob photo1)
{
    Session session = NewHibernateUtil.getSessionFactory().openSession();
    Transaction trans =null;
    Newsfeed nf = new Newsfeed(); // Pojo Class
    try 
    {
    trans=session.beginTransaction();
    nf.setUsername(uname);
    nf.setPhoto1(photo1);
    trans.commit();
    } 
    catch (Exception e) 
    {
    }
}
In Servlet,
Part filePart = request.getPart("filecover");
After this i am not sure how to add this using DAO savephoto1 method.. can anyone help me to proceed.. i need to store image in mySQL blob field and not the path..
When operating with large files (blobs), you usually map them as byte arrays:
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
File file = new File("C:\test.png");
byte[] imageData = new byte[(int) file.length()];
try {
    FileInputStream fileInputStream = new FileInputStream(file);
    fileInputStream.read(imageData);
    fileInputStream.close();
} catch (Exception e) {
    e.printStackTrace();
}
ImageWrapper image = new ImageWrapper();
image.setImageName("test.jpeg");
image.setData(imageData);
session.save(image);    //Save the data
session.getTransaction().commit();
HibernateUtil.shutdown();
You've got a full example, including reading the image, here: http://howtodoinjava.com/2013/08/30/hibernate-example-of-insertselect-blob-from-database/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With