环境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/htmlcharset=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: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()
}
%>
<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>
jsp是靠加载图片路径来显示图片的,图片可以保存在项目中,也可以保存到磁盘的某个路劲下。图片放webroot下,一般是webroot下建一个img或pic
文件夹专门存图。
jsp使用的时候<img
src"<%=request.getContextPath()%>/pic/mypic.gif"/>
这样就可以加载到图片了。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)