Path to JSP image

Asked

Viewed 596 times

1

I need to display an image inside the tag img.

It is a web project, running on Tomcat and Ubuntu Mate. I saved in bank as String the path to 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, someone, please, would be able to explain to me what is wrong and what should be done to correct?

  • If it was saved in the bank as /opt/imagens/img.png it makes perfect sense to show off /opt/imagens/img.png, you have to consider what is the path/route to the HTTP server, you must have created the "mapping" for the static files, no?

  • Guilherme, I didn’t map, what would that be? This folder is outside the project, it is an operating system folder.

  • do you know how to point the images folder to a route on Tomcat Hosts? I will try to post an answer with example, maybe it will help

2 answers

0

I don’t know much about Tomcat, but I believe in its application exists the server.xml, in it there must be a place written something like:

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

...

</Host>

So inside you could add:

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

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

    ...

</Host>

I guess I’ll have to restart your webapp

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

 http://localhost/imagens/1.jpg
  • In case, I was looking for something related to Servlets. I can’t change Tomcat settings. Even if I have to copy the image to some folder inside the application, something like that...

  • @Mayconstanguine has yes how to do direct by servelets, I will try to create an explanation on the subject, maybe not need to change anything.

  • Thank you, I’ll be waiting for your explanation.

0


Thank you all, including William for your attention.

The solution found 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, JSP displays 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 do what I need. =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.