Springboot does not render image (only if restarting)

Asked

Viewed 131 times

2

I have an entity called Product that has only Title, Price and wayImage, the latter guards the way in which the product image is saved. Upon receiving this form data my service executes this code:

public void addProduto(Produto produto, MultipartFile imagem) {
    String caminho = "/img/" + produto.getTitulo().replaceAll(" ", "") + ".jpg";
    produto.caminhoImagem = caminho;
    UsingFileUtils.salvarImagem(caminho, imagem);

    repo.save(produto);
}

Remove all title spaces and send to the Usingfileutils class that does this:

public static void salvarImagem(String caminho, MultipartFile imagem) {
    File file = new File("src/main/resources/static"+caminho);
    try {
        FileUtils.writeByteArrayToFile(file,imagem.getBytes());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

When doing this, it is redirected to the page with all products, but the image is not rendered, only if I restart the server, then it appears normally. The listing html looks like this:

<div class="card" style="width: 18rem;" th:each="produto : ${produtos}">
                <img class="card-img-top" th:src="@{${produto.caminhoImagem}}">
                <div class="card-body">
                    <h5 class="card-title" th:text="${produto.titulo}"></h5>
                    <p class="card-text" th:text="${produto.preco}"></p>
                    <a href="#" class="btn btn-primary">Quero</a>
                </div>
            </div>

What can I do to not have to restart the server to render the images?

1 answer

0

The problem is that second this post, the briefcase static is only loaded on application startup by Spring Boot, any changes in the contents of this folder will only be reflected on the next server startup.

That said, possible solutions:

1) Place your images in another folder that sensitizes Tomcat to restart automatically and, via Maven, copy them to the folder static original. This solution is here.

2) Use the Spring Content, that automates this process of storing and recovering static resources in the Spring environment. Take a read in this post.

Browser other questions tagged

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