5

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..

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

1 Comment

I am not trying to read an image from path, i am getting an image from User and trying to save user uploaded image

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.