Java: Vaadin Flow - Couldn't find route for 'avatars/... .png'

Viewed 97

I'm currently trying to create a Avatar-Upload-Field.

Therefore I've created setUpAvatarUpload like this:

public VerticalLayout setUpAvatarUpload() {

    VerticalLayout window = new VerticalLayout();
    FileBuffer buffer = new FileBuffer();
    Upload upload = new Upload(buffer);
    upload.addClassName("avatar_upload_field");
    upload.setAcceptedFileTypes("application/png", ".png", "application/jpg", ".jpg");
    upload.setAutoUpload(false);

    Button uploadButton = new Button("Avatar hochladen...");
    uploadButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
    upload.setUploadButton(uploadButton);

    upload.addSucceededListener(event -> {
        InputStream fileData = buffer.getInputStream();
        File uploadedFile = new File("src/main/resources/META-INF/resources/avatars/" + buffer.getFileName());

        try {
            OutputStream stream = new FileOutputStream(uploadedFile);
            stream.write(fileData.readAllBytes());
            uploadedFile.getParentFile().mkdirs();
            uploadedFile.createNewFile();
            stream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

        userService.setAvatar("avatars/" + buffer.getFileName(), currentUser.getId());
        UI.getCurrent().getPage().reload();

    });

    window.add(upload);
    return window;

}

And it actually works - it writes the correct path of the file into the h2-database and it also creates a new Instance of the Image inside the avatars/ - directory.

But here is the problem: As soon as I want to reload the page it won't show me the new avatar - it only shows the empty field with the name of the image.

I also get a Error-Message saying for example:

Couldn't find route for 'avatars/Resident_Evil_Village.jpg'

So it obviously couldn't find the image inside the directory - even if it's there.

I can reload as often as I want - no new avatar will be shown..

But as soon as I restart the programm it will show the new Image without any problems.

So it seems like it's a sort of "reload" or "flush"-problem.

Can you help me out here?

Thank you in Advance!

Edit: I think I need a StreamResource in some sort of way. But I have no idea how to implement it - if someone can help out here, I would be very thankful.

0 Answers
Related