用JSP从数据库中读取二进制图片并显示在网页上
环境mysql+tomcat:
先在mysql下建立如下的表. 并存储了二进制图像(二进制格式存储图片可以参考我的另一篇博客:https://www.cnblogs.com/ming-4/p/11869825.html)
mysql命令如下:
CREATE TABLE photo ( photo_no int(6) unsigned NOT NULL auto_increment, image blob, PRIMARY KEY (`photo_no`) )
把show.jsp放在tomcat目录下. show.jsp作用:从数据库中读出blob
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/hua?user=root&password="; Connection con = DriverManager.getConnection(URL); 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("image"); long size = b.length(); byte[] bs = b.getBytes(1, (int)size); OutputStream outs = response.getOutputStream(); outs.write(bs); outs.flush(); rs.close(); } } finally{ con.close(); } %>
把如下文件放在show.jsp的同一目录下:
index.html文件如下:
<HTML> <HEAD> <TITLE> 图像测试 </TITLE> </HEAD> <BODY> <TABLE> <TR> <TD>图像测试</TD> </TR> <TR> <TD><img src="show.jsp?photo_no=1"></TD> //更改1这个参数,可以显示数据库中的其他图片 </TR> </TABLE> </BODY> </HTML>