Serve an image from Servlet 3.0 contentType="multipart / form-data"

1

Greetings community! I pose the following problem, I have an image in a BBDD (format bytea[] ) and I want to serve an answer to show that image in my HTML. I do not have routes or directories, just the image in the database. It looks something like this:

  

cUpload.dameFoto () // returns my image in inputStream format.

I have tried to change the ContentType with image format "imagen/jpg" but I can not get the output in my javascript . Thanks in advance for your collaboration

 public void doPost(HttpServletRequest request, HttpServletResponse response){      

        OutputStream out;
        BufferedImage bI;
        int nRead;          
        InputStream is;


    try {                                                   

        response.setContentType("multipart/form-data");         

        out = response.getOutputStream();

        is = cUpload.dameFoto();

        bI = ImageIO.read(is);
        ImageIO.write(bI, "png", out);


    } catch (IOException | ServletException e) {
        System.err.println("Error en la respuesta de salida uploadServlet: " + e.getMessage());
    }

}

    
asked by mandel1985 19.12.2017 в 17:28
source

1 answer

0

If you are not going to use the conversion capabilities of ImageIO, for example convert from jpg to gif, etc, it would be better to treat the InputStream as binary and write it as binary too:

int c;
while ((c = in.read()) != -1) {
    out.write(c);
}

With ImageIO it will get complicated if you later want to use other formats.

Use the MIME type image/png or image/jpeg depending on the type of image you want to use. Call out.flush () to finish sending all the content of the image.

To show the image in your HTML you need to use the URL that downloads the image in your <img ... :

<img src="http://servidor.com/servlet-de-imagenes/foto.png" ...

to name your image add the header (http header):

Content-Disposition: filename="foto.png"

In the servlet:

response.setHeader("Content-Disposition", "filename=" + nombreDeArchivo);

    
answered by 19.12.2017 в 20:45