JSP读取Oracle数据库里的图片Blob字段并显示在页面上

The original website:http://longdick.iteye.com/blog/315279

 

/**

*  转载请注明作者longdick    http://longdick.iteye.com

*

*/

 

首先定义一个读取Oracle数据库的Blob字段并把字节写入一个输出流的方法:

 

 

Java代码
  1. public static void writeImg(OutputStream os) {   
  2.         Connection con;   
  3.         try {   
  4.             con = ConnectionFactory.getConnection();   
  5.             Statement stmt = con.createStatement();   
  6.             ResultSet rs = stmt.executeQuery("select pic from blob_table where b_id=1");   
  7.             byte[] b = new byte[1024];   
  8.             if (rs.next()) {   
  9.                 Blob blob = rs.getBlob(1);   
  10.                 InputStream is = blob.getBinaryStream();   
  11.                 int i = 0;   
  12.                 while ((i = is.read(b)) != -1) {   
  13.                     os.write(b, 0, i);   
  14.                 }   
  15.                 os.close();   
  16.                 is.close();   
  17.             }   
  18.             rs.close();   
  19.             stmt.close();   
  20.             con.close();   
  21.         } catch (Exception e) {   
  22.             e.printStackTrace();   
  23.         }   
  24.     }  
public static void writeImg(OutputStream os) {
		Connection con;
		try {
			con = ConnectionFactory.getConnection();
			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("select pic from blob_table where b_id=1");
			byte[] b = new byte[1024];
			if (rs.next()) {
				Blob blob = rs.getBlob(1);
				InputStream is = blob.getBinaryStream();
				int i = 0;
				while ((i = is.read(b)) != -1) {
					os.write(b, 0, i);
				}
				os.close();
				is.close();
			}
			rs.close();
			stmt.close();
			con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

 

然后做一个servlet,在doGet方法里调用writeImg方法

 

Java代码
  1. public void doGet(HttpServletRequest request, HttpServletResponse response)   
  2.             throws ServletException, IOException {   
  3.            
  4.         DBOperator.writeImg(response.getOutputStream());   
  5.            
  6.     }  
public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		DBOperator.writeImg(response.getOutputStream());
		
	}

 

 

最后只需要在显示的jsp页面里面定义img标签的src属性为servlet的访问地址就可以了:

 

Html代码
  1. <img src="servlet/newServlet"  >  

 

你可能感兴趣的:(jsp)