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

來源:互聯網
上載者:User

環境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>
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.