所以我尝试将blob图像保存到数据库中,并在点击“查看”href后显示它。但我不知道为什么这张照片无法看到。它保存在mysql数据库中......
retrieve_image.jsp:
<%@ page import="java.sql.*,model.Upload,java.io.*,java.util.*" %>
<HTML>
<table border="1">
<tr><th>ID</th><th>Image</th></tr>
<%
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/backup","root","mysql");
Statement stmt=con.createStatement();
String strQuery = "select * from contacts";
ResultSet rs = stmt.executeQuery(strQuery);
while(rs.next()){
%>
<tr>
<td><%=rs.getInt("contact_id")%></td>
<td>
<img src="RetrieveImages.java?id=<%=rs.getInt(1)%>" width="100" height="100">
</a></td>
</tr>
<%
}
rs.close();
con.close();
stmt.close();
}
catch(Exception e)
{
e.getMessage();
}
%>
</table>
</HTML>
RetrieveImages是一个servlet,其请求调度程序转到...
<%@page import="java.sql.Blob"%>
<%@page import="java.io.OutputStream"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@ page import="model.Upload" %>
<%
String contact_id = request.getParameter("contact_id");
String dbURL = "jdbc:mysql://localhost/backup";
String dbUser = "root";
String dbPass = "mysql";
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(dbURL, dbUser, dbPass);
PreparedStatement ps = con.prepareStatement("select * from contacts where contact_id=?");
ps.setString(1, contact_id);
ResultSet rs = ps.executeQuery();
if(rs.next()){
Blob blob = rs.getBlob("photo");
byte byteArray[] = blob.getBytes(1, (int)blob.length());
response.setContentType("image");
OutputStream os = response.getOutputStream();
os.write(byteArray);
os.flush();
os.close();
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(con != null){
try{
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
%>
在我的java bean中,我将contact_id和照片作为归属