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!!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…