简体   繁体   中英

Display an image from a byte array in jsp

I´m developed an web aplication in netbeans using html and jsp, and well I have to display a image from a databese in a index.

There is the method in the class that manager the database

public byte[] getImg(Connection connect, User user) throws SQLException {
        byte[] blobAsBytes = null;

        Statement statement = null;
        ResultSet rs = null;

        statement = connect.createStatement();
        rs = statement.executeQuery("select * from user");
        while (rs.next()) {
            if (rs.getString("nickName").equals(user.getNickName())) {

                Blob blob = rs.getBlob("img");
                int blobLength = (int) blob.length();
                blobAsBytes = blob.getBytes(1, blobLength);


                blob.free();
            }
        }
        return blobAsBytes;
    }

Then I try to use it in a jsp page.

 <jsp:useBean id="database" scope="session" type="Datos.ControlDatos"/>
 <jsp:useBean id="access" scope="session" type="Datos.DataAccess"/>

        <%
            byte[] imgData = database.getImg(access.createConnection(),user);
            response.setContentType("image/jpeg");
            response.getOutputStream().write(imgData);            

         %>

The problem is that I get this exception:

org.apache.jasper.JasperException: java.lang.IllegalStateException: getOutputStream() has already been called for this response
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:585)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

So there is a way to display the image as a byte array in a jsp page?

Your JSP page is already streamling HTML to the client. You can only return one response type per request. Instead of trying to embed bytes into the page you need to add an img tag pointing to another URL which serves up a new response of type image/jpeg.

You should make a servlet or jsp that writes the byte[] to the response, and create an img element in the html page that show the generated image.

Here's how to write an image to response:

Writing image to servlet response with best performance

And here's how to get the image from the servlet to the html page:

Pass dynamic image to JSP with servlet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM