JSP 實現 之 讀取數據庫顯示圖片


用JSP從數據庫中讀取圖片並顯示在網頁上 環境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: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> 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM