我想使用Hibernate将用户上传的图像存储在数据库中。但我不知道该怎么做..这是我的代码
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)
{
}
}
在Servlet中,
Part filePart = request.getPart("filecover");
在此之后我不知道如何使用DAO savephoto1方法添加它..任何人都可以帮助我继续..我需要将图像存储在mySQL blob字段而不是路径..
答案 0 :(得分:1)
使用大文件(blob)时,通常将它们映射为字节数组:
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();
您已经有了完整的示例,包括阅读图片,在这里:http://howtodoinjava.com/2013/08/30/hibernate-example-of-insertselect-blob-from-database/