用JSP從數據庫中讀取圖片並顯示在網頁上


<1>先在mysql下建立如下的table. 並insert圖像. 
mysql.sql文件如下: 

[sql]  view plain  copy
 
  1. CREATE TABLE photo (   
  2. photo_no int(6) unsigned NOT NULL auto_increment,   
  3. image blob,   
  4. PRIMARY KEY (`photo_no`)   
  5. )   


<2>把show.jsp放在tomcat的任意目錄下. show.jsp作用:從數據庫中讀出blob,並產生image/jpg. 

show.jsp文件如下: 

 

[html]  view plain  copy
 
  1. <%@ page contentType="text/html; charset=gbk" %>   
  2. <%@ page import="java.io.*"%>   
  3. <%@ page import="java.sql.*, javax.sql.*" %>   
  4. <%@ page import="java.util.*"%>   
  5. <%@ page import="java.math.*"%>   
  6. <%   
  7. String photo_no = request.getParameter("photo_no");   
  8. //mysql連接   
  9. Class.forName("com.mysql.jdbc.Driver").newInstance();   
  10. String URL="jdbc:mysql://localhost:3306/job?user=root&password=111111";   
  11. Connection con = DriverManager.getConnection(URL);   
  12.   
  13. //oracle連接   
  14. //String URL="jdbc:oracle:thin@localhost:1521:orcl2";   
  15. //user="system";   
  16. //password="manager";   
  17. //Connection con = DriverManager.getConnection(URL,user,password);   
  18.   
  19.   
  20. try{   
  21. // 准備語句執行對象   
  22. Statement stmt = con.createStatement();   
  23. String sql = " SELECT * FROM PHOTO WHERE photo_no = "+ photo_no;   
  24. ResultSet rs = stmt.executeQuery(sql);   
  25. if (rs.next()) {   
  26. Blob b = rs.getBlob("photo_image");   
  27. long size = b.length();   
  28. //out.print(size);   
  29. byte[] bs = b.getBytes(1, (int)size);   
  30. response.setContentType("image/jpeg");   
  31. OutputStream outs = response.getOutputStream();   
  32. outs.write(bs);   
  33. outs.flush();   
  34. rs.close();   
  35. }   
  36. else {   
  37. rs.close();   
  38. response.sendRedirect("./images/error.gif");   
  39. }   
  40. }   
  41. finally{   
  42. con.close();   
  43. }   
  44. %>   

 

 

<3>把如下文件放在show.jsp的同一目錄下. 
index.html文件如下: 

 

[html]  view plain  copy
 
    1. <html>  
    2. <head>  
    3. <title> 圖像測試 </title>  
    4. </head>  
    5. <body>  
    6. <table>  
    7. <tr>  
    8.     <td>  
    9.         圖像測試  
    10.     </td>  
    11. </tr>  
    12. <tr>  
    13.     <td>  
    14.         <img src="show.jsp?photo_no=2">  
    15.     </td>  
    16. </tr>  
    17. </table>  
    18. </body>  
    19. </html>  


免責聲明!

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



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