Path to image in JSP

1

I need to display an image inside the img tag.

It's a web project, running on Tomcat and Ubuntu Mate. I save in bank as String the path of where the image is:

"/opt/imagens/img.png"

To display, I put it this way

<img src="<%=urlImg.getUrl()%>" >

urlImg.getUrl() returns "/opt/imagens/img.png"

The image does not appear, would someone please explain to me what is wrong and what should be done to correct it?

    
asked by anonymous 13.12.2017 / 16:19

2 answers

0

Thanks to everyone, including Guilherme for the attention.

The solution was to generate a string with the bytes of the image and display directly.

The method I created to return the string, from the image file:

public static String convertPngToByteString(String path) {
        String img = "";
        try{
            File imagem = new File(path);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            BufferedImage bi = ImageIO.read(imagem);
            ImageIO.write(bi, "png", bos);
            bi.flush();
            byte[] imageInByte = bos.toByteArray();
            bos.close();
            img = DatatypeConverter.printBase64Binary(imageInByte);
        } catch(Exception e) {
            e.printStacktrace();
        }
        return img;
    }

With this method, in the JSP display as follows:

<img src="<%="data:image/png;Base64,"+ImagemUtil.convertPngToByteString(urlImg.getUrl())%>" width="213" height="160" id="imgFoto" />

It may not be the best way, but it does what it takes. =)

    
14.12.2017 / 15:10
0

I do not understand much about Tomcat, but I believe that in your application there is server.xml , there should be a location written something like:

<Host name="localhost"  appBase="webapps" ...>

...

</Host>

Then inside you could add:

<Host name="localhost"  appBase="webapps" ...>

    <Context docBase="/opt/imagens" path="/imagens" />

    ...

</Host>
  

I think you have to restart your webapp

Then after rebooting the images are accessible via the HTTP path, something like:

 http://localhost/imagens/1.jpg
    
13.12.2017 / 17:50