0

经过长时间的尝试,我终于可以成功上传一张图片到一个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。很奇怪的行为!!

4

1 回答 1

0

使用调试器或代码中的跟踪来查看它执行了什么。

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

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

于 2012-07-30T15:59:08.473 回答