我正在使用SQLServerr 2012 Management Studio。我想从数据库中检索图像并在浏览器中显示它。我已经采用了图像的数据类型是图像数据类型,因为它没有选择采用blob数据类型。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//PrintWriter pw = response.getWriter();
String connectionUrl = "jdbc:sqlserver://localhost; databaseName=JDBC1; user=sa; password=123;";
java.sql.Connection con=null;
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
Statement st1=con.createStatement();
ResultSet rs1 = st1.executeQuery("select image from image_table");
String imgLen="";
if(rs1.next()){
imgLen = rs1.getString(1);
System.out.println(imgLen.length());
}
rs1 = st1.executeQuery("select image from image_table");
if(rs1.next()){
int len = imgLen.length();
byte [] rb = new byte[len];
InputStream readImg = rs1.getBinaryStream(1);
int index=readImg.read(rb, 0, len);
System.out.println("index"+index);
st1.close();
response.reset();
response.setContentType("image/jpg");
response.getOutputStream().write(rb,0,len);
response.getOutputStream().flush();
}
}
catch (Exception e){
e.printStackTrace();
}
}
}