日期:2014-05-16  浏览次数:20544 次

JSP使用JDBC显示BLOB图片文件

<%@page import="java.io.PrintWriter"%>  
<%@page import="java.io.OutputStream"%>  
<%@page import="java.io.InputStream"%>  
<%@page import="java.sql.ResultSet"%>  
<%@page import="net.sysmain.common.ConnectionManager"%>  
<%@page import="java.sql.PreparedStatement"%>  
<%@page import="java.sql.Connection"%>  
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
<%  
    response.reset();  
    String guid = request.getParameter("guid");  
    Connection conn = null;  
    PreparedStatement ps = null;  
    ResultSet rs = null;  
    InputStream is = null;  
    OutputStream os = null;  
    try{  
        conn = ConnectionManager.getInstance().getConnection();  
        ps = conn.prepareStatement("select img from user where guid=?");  
        ps.setString(1, guid);  
        rs = ps.executeQuery();  
        if(rs.next()){  
            is = rs.getBinaryStream(1);  
        }  
        response.setContentType("image/jpeg");  
        os = response.getOutputStream();  
        int num;  
        byte buf[] = new byte[1024];  
        while(   (num=is.read(buf))!=-1   ){  
            os.write(buf, 0, num);  
        }  
        os.flush();  
        is.close();  
        os.close();  
    }catch(Exception e){  
        e.printStackTrace();  
    }finally{  
        ConnectionManager.close(conn,ps,rs);  
    }  
%>  
?

页面显示代码:

?

?

<img style="width:73px" src="<%=request.getContextPath() %>/showImg.jsp?guid=<%=guid %>" />