问题
After a long trial ,I finally successfully able to upload an image to an oracle database
. At least my code says so. However to check whether the image has been successfully I wrote a servlet
. After running the servlet
I get a black screen in my browser and nothing else. The servlet
code is:
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);
}
}
By the way, as I am totally new to this, I took extensive help from this File upload and display demo.
EDIT : I get the black screen if only viewed from FF , but if viewed from internal web browser of Eclipse it shows me a single word upload
. Very strange behaviour!!
回答1:
Use a debugger, or traces in the code, to see what it executes.
Use Firebug to see what the response contains.
And fix the reading and writing from the blob to the output stream: InputStream.read()
doesn't necessarily read all the bytes at once. It returns the number of bytes that were actually read. You should loop until this method returns -1 to indicate that everything has been read. Read the Java IO tutorial.
来源:https://stackoverflow.com/questions/11724624/image-is-not-displayed-from-oracle-table-using-servlet