向数据库插入图片以及从数据库中读取图片并显示到jsp(数据库中存储的图片字段类型为Blob或image)
以前都是将图片的存储路径存在数据库中,这次学习了将图片以blob类型或image类型存储在数据库中,并从数据库中获取图片显示到jsp中。
表名为:tmp(员工表)
字段:id (员工id,int类型),pic(员工照片,blob类型),descs(照片文件名,varchar类型)
java bean类可以直接用Blob类型的属性接收pic字段,如Tmp类中有属性:private Blob photo;(也可以是其它类型,转换一下就OK)
下面是用struts2实现的读取图片并显示到jsp的代码,直接把方法写在Action中, 由于使用到response,一定要实现接口ServletResponseAware并实现setServletResponse方法, 否则response会报空指针异常。 struts2的上传图片并插入数据库方法还没写,以后整理。。。
public class ImageAction extends ActionSupport implements ServletResponseAware{ private static final String URL = "jdbc:mysql://localhost:3306/test?user=root&password=qweqwe1314&useUnicode=true"; private Connection conn = null; private PreparedStatement pstmt = null; private ResultSet rs = null; private int picID = 1; private ServletOutputStream sout; private HttpServletResponse response; public String execute() throws Exception { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); conn = (Connection) DriverManager.getConnection(URL); pstmt = (PreparedStatement) conn .prepareStatement("select pic from tmp where id=?"); pstmt.setInt(1, picID); // 传入要取的图片的ID rs = pstmt.executeQuery(); if (rs.next()) { Blob photo = (Blob) rs.getBlob("pic"); InputStream in = photo.getBinaryStream(); response.reset(); sout = response.getOutputStream(); byte[] b = new byte[1024]; int len = in.read(b); while (len != -1) { sout.write(b); len = in.read(b); } sout.flush(); sout.close(); in.close(); } return "success"; } public ServletOutputStream getSout() { return sout; } public void setSout(ServletOutputStream sout) { this.sout = sout; } @Override public void setServletResponse(HttpServletResponse arg0) { // TODO Auto-generated method stub this.response = arg0; } }
jsp只需用img标签,src为${sout}就可以将图片显示出来: <img src="${sout}"/>
以下是没有用struts2的两个方法, 分别是向数据库存入一张图片,从数据库读取一张图片
package com.image; import java.io.*; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.sql.DriverManager; import java.sql.ResultSet; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; public class BlobPros { private static final String URL = "jdbc:mysql://localhost:3306/test?user=root&password=qweqwe1314&useUnicode=true"; private Connection conn = null; private PreparedStatement pstmt = null; private ResultSet rs = null; private File file = null; public BlobPros() { } /** * 向数据库中插入一个新的BLOB对象(图片) * * @param infile * 要输入的数据文件 * @throws java.lang.Exception */ public void blobInsert(String infile) throws Exception { FileInputStream fis = null; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); conn = (Connection)DriverManager.getConnection(URL); file = new File(infile); fis = new FileInputStream(file); // InputStream fis = new FileInputStream(infile); pstmt = (PreparedStatement)conn.prepareStatement("insert into tmp(descs,pic) values(?,?)"); pstmt.setString(1, file.getName()); // 把传过来的第一个参数设为文件名 // pstmt.setBinaryStream(2,fis,(int)file.length()); // //这种方法原理上会丢数据,因为file.length()返回的是long型 pstmt.setBinaryStream(2, fis, fis.available()); // 第二个参数为文件的内容 pstmt.executeUpdate(); } catch (Exception ex) { System.out.println("[blobInsert error : ]" + ex.toString()); } finally { // 关闭所打开的对像// pstmt.close(); fis.close(); conn.close(); } } /** * 从数据库中读出BLOB对象 * * @param outfile * 输出的数据文件 * @param picID * 要取的图片在数据库中的ID * @throws java.lang.Exception */ public void blobRead(String outfile, int picID) throws Exception { FileOutputStream fos = null; InputStream is = null; byte[] Buffer = new byte[4096]; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); conn = (Connection)DriverManager.getConnection(URL); pstmt = (PreparedStatement)conn.prepareStatement("select pic from tmp where id=?"); pstmt.setInt(1, picID); // 传入要取的图片的ID rs = pstmt.executeQuery(); rs.next(); file = new File(outfile); if (!file.exists()) { file.createNewFile(); // 如果文件不存在,则创建 } fos = new FileOutputStream(file); is = rs.getBinaryStream("pic"); int size = 0; /* * while(size != -1) { size = is.read(Buffer); //从数据库中一段一段的读出数据 * //System.out.println(size); if(size != -1) //-1表示读到了文件末 * fos.write(Buffer,0,size); } */ while ((size = is.read(Buffer)) != -1) { // System.out.println(size); fos.write(Buffer, 0, size); } } catch (Exception e) { System.out.println("[OutPutFile error : ]" + e.getMessage()); } finally { // 关闭用到的资源 fos.close(); rs.close(); pstmt.close(); conn.close(); } } public static void main(String[] args) { try { BlobPros blob = new BlobPros(); //blob.blobInsert("e:/llj/1.jpg"); // blob.blobInsert("C:Downloadsluozsh1.jpg"); blob.blobRead("e:/llj/2.jpg", 1); } catch (Exception e) { System.out.println("[Main func error: ]" + e.getMessage()); } } }