查询BLOB(图片)并通过流方式写入页面

//通过oracle中获取BLOB字段并且将BLOB字段中的图片显示在页面中。(流)
ResultSet rsset = null;
PreparedStatement pstmt = null; 
Connection conn = null; 
try { 
Class.forName("oracle.jdbc.driver.OracleDriver"); 
conn = DriverManager.getConnection 
("jdbc:oracle:thin:@10.1.7.79:1521:tjkf", "yhm", "mm");
String sql = "select FILE_CONTENT from UPLOAD_FILE u where u.ID = ?";
  pstmt = conn.prepareStatement(sql);
  pstmt.setString(1, zdz);
  rsset=pstmt.executeQuery();
  while(rsset.next())
{
   Blob blob=rsset.getBlob(1);
//获取blob字段==转化为流
    InputStream reader=blob.getBinaryStream(); 
   OutputStream writer = null;
try {
         //获取页面输出流,进行页面内容的写出
writer = response.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
byte buf[]=new byte[1024];
try {
for(int i=0;(i=reader.read(buf))>0;){
          //将读取的blob字段的流输出到页面中/通过页面输出流
          writer.write(buf,0,i);
    }
} catch (IOException e) {
e.printStackTrace();
}
  }
  } catch (ClassNotFoundException e) { 
   e.printStackTrace(); 
  } catch (SQLException e) { 
   e.printStackTrace(); 
} finally { 
    //关闭流
   try {
if(rsset != null) { 
     rsset.close(); 
rsset = null; 
}
    if(pstmt != null) { 
     pstmt.close(); 
     pstmt = null; 
    } 
    if(conn != null) { 
     conn.close(); 
     conn = null; 
    } 
   } catch (SQLException e) { 
    e.printStackTrace(); 
   } 
  } 
}
//将byte类型数组转化为Char类型数组
private char[] getChars (byte[] bytes) {
      Charset cs = Charset.forName ("UTF-8");
      ByteBuffer bb = ByteBuffer.allocate (bytes.length);
      bb.put (bytes);
      bb.flip ();
      CharBuffer cb = cs.decode (bb);
 
   return cb.array();
}

猜你喜欢

转载自liuzhiqiang19890403.iteye.com/blog/2025363