>데이터 베이스 >MySQL 튜토리얼 >把mysql读取的图片显示在jsp 页面上

把mysql读取的图片显示在jsp 页面上

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB원래의
2016-06-07 15:08:441215검색

先创建数据库 如: create table bcctphoto( photoid int primary key auto_increment, photoname varchar(50) NOT NULL, photo blob ); 2把show.jsp放在tomcat的任意目录下. show.jsp作用:从数据库中读出blob,并产生image/jpg. show.jsp文件如下: %@ page c

先创建数据库

如:

create table bcctphoto(
    photoid int primary key auto_increment,
    photoname    varchar(50)    NOT NULL,
    photo    blob
);


把show.jsp放在tomcat的任意目录下. show.jsp作用:从数据库中读出blob,并产生image/jpg.

show.jsp文件如下:





String photo_no = request.getParameter("photo_no");

//mysql连接
Class.forName("com.mysql.jdbc.Driver").newInstance();
String URL="jdbc:mysql://localhost:3306/bigdate?user=root&password=mysqladmin";
Connection con = DriverManager.getConnection(URL);

//oracle连接
//String URL="jdbc:oracle:thin@localhost:1521:orcl2";
//user="system";
//password="manager";
//Connection con = DriverManager.getConnection(URL,user,password);


try{
// 准备语句执行对象
Statement stmt = con.createStatement();

String sql = " SELECT * FROM PHOTO WHERE photo_no = "+ photo_no;
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
Blob b = rs.getBlob("photo_image");
long size = b.length();
//out.print(size);
byte[] bs = b.getBytes(1, (int)size);
response.setContentType("image/jpeg");
OutputStream outs = response.getOutputStream();
outs.write(bs);
outs.flush();
rs.close();
}
else {
rs.close();
response.sendRedirect("./images/error.gif");
}
}
finally{
con.close();
}
%>

把如下文件放在show.jsp的同一目录下.

index.html文件如下:



图像测试









图像测试
把mysql读取的图片显示在jsp 页面上




异常处理: 如果出现 getOutputStream() has already been called for this response


异常解析:这里是在释放在jsp中使用的对象,会调用response.getWriter(),因为这个方法是和response.getOutputStream()相冲突的!所以会出现以上这个异常。然后当然是要提出解决的办法,其实挺简单的,在使用完输出流以后调用以下两行代码即可:


解决方法:添加代码

  1. out.clear();  
  2. out = pageContext.pushBody(); 

如下代码:

  • //注意看以下几句的使用  
  • outs.flush();  
  • outs.close();  
  • outs=null;  
  • response.flushBuffer();  
  • out.clear();  
  • out = pageContext.pushBody(); 
  • 성명:
    본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.