经过长时间的尝试,我终于可以成功上传一张图片到一个oracle database
. 至少我的代码是这样说的。但是为了检查图像是否成功,我写了一个servlet
. 运行后servlet
,我的浏览器出现黑屏,没有别的。servlet
代码是:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DisplayImage extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:XE";
Connection con = DriverManager.getConnection(url,"system","root");
PreparedStatement ps = con.prepareStatement("select image from insertimage");
ResultSet rs = ps.executeQuery();
rs.next();
Blob b = rs.getBlob("image");
response.setContentType("image/jpeg");
response.setContentLength( (int) b.length());
InputStream is = b.getBinaryStream();
OutputStream os = response.getOutputStream();
byte buf[] = new byte[(int) b.length()];
is.read(buf);
os.write(buf);
os.close();
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
顺便说一句,由于我对此完全陌生,因此我从这个文件上传和显示演示中获得了广泛的帮助。
编辑:如果只从 FF 查看,我会得到黑屏,但如果从 Eclipse 的内部 Web 浏览器查看,它会显示一个单词upload
。很奇怪的行为!!