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"  >  

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值