使用servlet不会从Oracle表中显示图像

时间:2012-07-30 15:31:32

标签: image servlets oracle10g blob data-retrieval

经过长时间的试用,我终于成功将图片上传到了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);
}

  }

顺便说一下,由于我对此完全陌生,我从这个File upload and display demo获得了广泛的帮助。 编辑:如果仅从FF查看,我会看到黑屏,但如果从Eclipse的内部网络浏览器查看,它会向我显示一个单词upload。很奇怪的行为!!

1 个答案:

答案 0 :(得分:0)

使用调试器或代码中的跟踪来查看它执行的内容。

使用Firebug查看响应包含的内容。

并修复从blob到输出流的读取和写入:InputStream.read()不一定一次读取所有字节。它返回实际读取的字节数。您应该循环,直到此方法返回-1表示已读取所有内容。阅读Java IO tutorial