用JSP从数据库中读取图片并显示在网页上

作者:网络 来源:佚名 更新时间:2008-02-08 23:37:27 点击:
 

环境mysql+tomcat:

<1>先在mysql下建立如下的table. 并insert图像.

mysql.sql文件如下:

create table photo (
photo_no int(6) unsigned not null auto_increment,
image blob,
primary key (`photo_no`)
)

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

show.jsp文件如下:

<%@ page contenttype="text/html; charset=gbk" %>
<%@ page import="java.io.*"%>
<%@ page import="java.sql.*, javax.sql.*" %>
<%@ page import="java.util.*"%>
<%@ page import="java.math.*"%>

<%
string photo_no = request.getparameter("photo_no");

//mysql连接
class.forname("com.mysql.jdbc.driver").newinstance();
string url="jdbc:mysql://localhost:3306/job?user=root&password=111111";
connection con = drivermanager.getconnection(url);

//oracle连接
//string url="jdbc:oracle:thi[email protected]: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();
}
%>

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

index.html文件如下:

<html>
<head>
<title> 图像测试 </title>

</head>

<body>
<table>
<tr>
<td>图像测试</td>
</tr>
<tr>
<td><img src="show.jsp?photo_no=2"></td>
</tr>
</table>

</body>
</html>