先創(chuàng)建數(shù)據(jù)庫 如: create table bcctphoto( photoid int primary key auto_increment, photoname varchar(50) NOT NULL, photo blob ); 2把show.jsp放在tomcat的任意目錄下. show.jsp作用:從數(shù)據(jù)庫中讀出blob,并產(chǎn)生image/jpg. show.jsp文件如下: %@ page c
先創(chuàng)建數(shù)據(jù)庫
如:
create table bcctphoto(
photoid int primary key auto_increment,
photoname varchar(50) NOT NULL,
photo blob
);
<2>把show.jsp放在tomcat的任意目錄下. show.jsp作用:從數(shù)據(jù)庫中讀出blob,并產(chǎn)生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/bigdate?user=root&password=mysqladmin";
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{
// 準(zhǔn)備語句執(zhí)行對象
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文件如下:
圖像測試 |
異常處理: 如果出現(xiàn) getOutputStream() has already been called for this response
異常解析:這里是在釋放在jsp中使用的對象,會調(diào)用response.getWriter(),因為這個方法是和response.getOutputStream()相沖突的!所以會出現(xiàn)以上這個異常。然后當(dāng)然是要提出解決的辦法,其實挺簡單的,在使用完輸出流以后調(diào)用以下兩行代碼即可:
解決方法:添加代碼
如下代碼:
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com