我正在尝试将MySQL服务器上的图像显示到浏览器上。但是以下代码可在Internet Explorer上运行,但不能在Chrome和Mozilla Firefox浏览器上运行。
我是JSP的新手,我已经尝试过该问题的代码,但是没有用。Displaying image in jsp from database
`<%@ include file="connect.jsp" %>
<%@page import="java.sql.*,java.io.*"%>
<%@ page import="java.sql.*,java.io.*,java.util.*" %>
<%
try{
int id = Integer.parseInt(request.getParameter("id"));
Statement st=connection.createStatement();
String strQuery = "select image from user where id="+id+"" ;
ResultSet rs = st.executeQuery(strQuery);
String imgLen="";
if(rs.next())
{
imgLen = rs.getString(1);
}
rs = st.executeQuery(strQuery);
if(rs.next())
{
int len = imgLen.length();
byte [] rb = new byte[len];
InputStream readImg = rs.getBinaryStream(1);
int index=readImg.read(rb, 0, len);
st.close();
response.reset();
response.getOutputStream().write(rb,0,len);
response.getOutputStream().flush();
}
}
catch (Exception e){
e.printStackTrace();
}%>
答案 0 :(得分:0)
要从SQL数据库中检索多个图像并显示在JSP页面中,可以执行以下操作:
<%
int id = Integer.parseInt(request.getParameter("imgid"));
try {
Connection con=DriverManager.getConnection("jdbc:sqlserver://LAPTOP-UT57IH20\\SQLEXPRESS14;databaseName=Student;user=sa;password=ccms@321");
Statement st = con.createStatement();
String strQuery = "select image from login_users where id='" + id + "'";
ResultSet rs = st.executeQuery(strQuery);
String imgLen="";
if(rs.next()) {
imgLen = rs.getString(1);
}
rs = st.executeQuery(strQuery);
if(rs.next()) {
byte[] bytearray = new byte[4096];
int size=0;
InputStream sImage = rs.getBinaryStream(1);
response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1) {
response.getOutputStream().write(bytearray,0,size);
}
response.getOutputStream().flush();
response.getOutputStream().close();
response.flushBuffer();
sImage.close();
rs.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
%>