1.将二进制数据写入数据库(hibernate):
//FileInputStream str;
try {
//str = new FileInputStream(enBO.getFileName());
InputStream fs=enBO.getFile().getInputStream();
PreparedStatement pstmt;
pstmt = this.getSession().connection().prepareStatement("insert into file_content values("+enBO.getAttachmentId()+",?)");
//pstmt.setBinaryStream(1,str,str.available());
pstmt.setBinaryStream(1,fs,fs.available());
pstmt.execute();
pstmt.close();
fs.close();
//str.close();
}
catch (IOException e) {
e.printStackTrace();
}
catch (HibernateException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
2.二进制文件数据下载
FileContent fileContent = contactService.getFileContent(fileContentId);
response.reset();
//
response.addHeader("Content-Disposition", "attachment;filename="
+ fileContent.getAttachment().getFileName());
response.addHeader("Content-Length", ""+fileContent.getFileContent().length);
response.setContentType("bin");
OutputStream toClient = new BufferedOutputStream(response
.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(fileContent.getFileContent());
toClient.flush();
toClient.close();
本文介绍了如何使用Hibernate将二进制数据写入数据库的方法,包括通过输入流获取文件内容并将其插入到指定的数据库表中。此外,还提供了从数据库读取二进制文件数据并供用户下载的具体实现。
441

被折叠的 条评论
为什么被折叠?



