Images to show with Vaadin 14

Viewed 503

I'm writing this post because I need some help. I'm having trouble display an image depending on a specific path in my App.

Basically what it's doing: I have a module named Sector, and each Sector can have an image related to it. When I use the Upload component of Vaadin, I save the path of the image to a table in my database so that it can display the picture chosen before.

The actual path of the image is weird, it seems that Vaadin copies the image to a dynamic random folder. It seems logical that it can't use the actual path of the image.

But here's the problem: The path is well entered in the Database, but when I reload the page (F5), Vaadin can't shows the image anymore. Which upsets me since it should display it well.

The path that Vaadin creates with the uploaded image : VAADIN/dynamic/resource/2/c1ef7b9d-8f2b-4354-a97e-fe1fd4e868e7/551434.jpg

I can put some code if it can help.

The screenshots show what it's doing once I'm refreshing the browser page.

The image is being uploaded

After refreshing the page

Here is the part of the code where I handle the upload image:

upload.addSucceededListener(e -> {
            Component component = createComponent(e.getMIMEType(),
                    e.getFileName(), buffer.getInputStream());
            showOutput(e.getFileName(), component, output);
            //imgUpload = (Image) component;
            InputStream inputStream = buffer.getInputStream();
            targetFile = new File(PATH + currentProjetId + "\\secteur" + currentSecId + "\\photoSec.png");
            try {
                FileUtils.copyInputStreamToFile(inputStream, targetFile);
            } catch (IOException e1) {
                e1.printStackTrace();
                Notification.show("Error");
            }
            System.out.println("PATH : " + targetFile.getPath());
        });
1 Answers

I think you are using an in-memory resource that's discarded when you refresh the view. You have to take the contents of the file and save it in a file inside a directory in the server's file system. Here's an example:

FileBuffer receiver = new FileBuffer();
Upload upload = new Upload(receiver);
upload.setAcceptedFileTypes("text/plain");
upload.addSucceededListener(event -> {
    try {
      InputStream in = receiver.getInputStream();
      File tempFile = receiver.getFileData().getFile();
      File destFile = new File("/some/directory/" + event.getFileName());
      FileUtils.moveFile(tempFile, destFile);
      
    } catch (IOException e) {
      e.printStackTrace();
      Notification.show("Error").
    }
});
Related