数据库为oracle,图片存储类型为Blob。
要想往数据库里插入,需要两个步骤:
1、插入空值(empty_blob());
2、更新Blob字段。
DAO如下:
public class BookDaoJdbcImpl extends JdbcDaoSupport implements BookDao {
//1、插入空值
public void addBook(Book book) {
String sql = "INSERT INTO bookinfo(id, coverimg) " +
"VALUES(" + book.getId() + ",empty_blob())";
this.getJdbcTemplate().execute(sql);
}
//2、更新图片
public void upDateCoverImg(final int id, final File img) throws Exception {
final FileInputStream fis = new FileInputStream(img);
this.getJdbcTemplate().update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection){
PreparedStatement ps = null;
try {
ps = connection.prepareStatement("UPDATE bookinfo SET coverimg=? WHERE id=?");
ps.setBinaryStream(1, fis, fis.available());
ps.setInt(2, id);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return ps;
}
});
}
//获取图片输入流,用于读取图片
public InputStream getCoverImg(int id) {
InputStream inputStream;
String sql = "SELECT coverimg FROM bookinfo WHERE id=" + id;
inputStream = (InputStream)this.getJdbcTemplate().execute(sql, new PreparedStatementCallback() {
public Object doInPreparedStatement(PreparedStatement pstmt) throws SQLException, DataAccessException {
ResultSet rs = pstmt.executeQuery();
BufferedInputStream ins = null;
if (rs.next()) {
Blob blob = rs.getBlob(1);
try {
ins = new BufferedInputStream(blob.getBinaryStream());
} catch (Exception e) {
}
}
return ins;
}
});
return inputStream;
}
}
AddBookAction如下:
public class AddBookAction {
//inject
private BookDao bookDao;
//input
private Book book;
private File uploadFile; //图片上传控件
public String execute() throws Exception {
//添加基本图书信息
bookDao.addBook(book);
//更新图片BLOB
bookDao.upDateCoverImg(book.getId(), uploadFile);
return "success";
}
//getter and setter
}
AddBookAction配置:
<action name="addBook" class="AddBookAction">
<interceptor-ref name="fileUpload"></interceptor-ref>
<interceptor-ref name="basicStack"></interceptor-ref>
<result name="success">/book/bookInfo.jsp?id=${id}</result>
</action>
至此完成图片上传核心编码。
图片读取与显示
DAO见上面部分。
GetImageAction如下:
public class GetImageAction extends BaseAction {
//inject
private BookDao bookDao;
//input
private int id;
//output
private InputStream coverImg;
public String execute() {
coverImg = bookDao.getCoverImg(id);
return "success";
}
//getter and setter
}
GetImageAction配置如下:
<action name="getImg" class="GetImageAction">
<result name="success" type="stream">
<param name="inputName">coverImg</param>
</result>
</action>
JSP页面使用:
<img src="${pageContext.request.contextPath}/getImg?id=<s:property value='book.id'/>" width="100" height="120"/>
new FileInputStream(img) setBinaryStream()方法
上传:File------------------------------------------>FileInputStream 流------------------------------------------>blob类型
getBinaryStream() read() response
显示:blob类型----------------------------------->BufferedInputStream流 --------------->byte[]---------------------------->OutputStream().write()