首页 > 代码库 > 将图片以Blob格式存入数据库,再通过Servlet显示到界面

将图片以Blob格式存入数据库,再通过Servlet显示到界面

1:为了方便测试,直接将1.png图片存入到数据库中.

public static void storePicBlog() throws FileNotFoundException, SQLException, IOException{        Connection conn = JdbcUtil.getConnection();        File f = new File("1.jpg");        FileInputStream fis = new FileInputStream(f);                String sql = "insert into pic_test(id,zp) values(?,?)";                PreparedStatement ps = conn.prepareStatement(sql);                ps.setString(1, StringUtil.getUUID());        ps.setBinaryStream(2, fis, (int)f.length());                ps.executeUpdate();                fis.close();        ps.close();        JdbcUtil.release(conn);    }

2:进行读取操作

public static InputStream getPicInputStream(){        String id = "f304733361e243779b2340afe20e62bf";                 Connection conn = JdbcUtil.getConnection();                  PreparedStatement ps = null;                  ResultSet rs = null;                  InputStream is = null;                  String sql = "select zp from pic_test where id= ?";                 try {                        ps = conn.prepareStatement(sql);                        ps.setString(1, id);                        rs = ps.executeQuery();                        if(rs.next()){                is = rs.getBlob("zp").getBinaryStream();            }                    } catch (SQLException ex) {            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);        }finally{            try {                if(null!=ps){                    ps.close();                }            } catch (SQLException ex) {                Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);            }            try {                if(null!=rs){                    rs.close();                }            } catch (SQLException ex) {                Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);            }            JdbcUtil.release(conn);        }                         return is;    }

3:测试Servlet,通过浏览器访问此Servlet,一定要设置:

response.setContentType("image/jpeg");浏览器中才可以将图片显示出来
protected void processRequest(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        response.setContentType("image/jpeg");                InputStream is = Test.getPicInputStream();                if(null!=is){                       OutputStream os = response.getOutputStream();                        int len;                        byte buf[] = new byte[1024];                        while((len=is.read(buf))!=-1){                os.write(buf, 0, len);            }                        is.close();            os.close();        }            }

 

将图片以Blob格式存入数据库,再通过Servlet显示到界面