Uploader Error Message

Hi everyone,

i would like to translate the error message after upload was not succesfull.

We have tried to add a limit and uploaded an image which is 2MB, but the question is why did it work? Mus we throw an exception in inMemoryUploadHandler? But whats the point of setMaxFileSize?

InMemoryUploadHandler inMemoryHandler = UploadHandler.inMemory(
                (metadata, data) -> {
                   //save file
                    if (success) {
                        NotificationUtil.success("Die Datei wurde erfolgreich hochgeladen.");
                    } else {
                        NotificationUtil.error("Die Datei konnte nicht hochgeladen werden.");
                    }
                });
        upload = new Upload(inMemoryHandler);
        upload.setAutoUpload(true);
        upload.setDropAllowed(true);

        upload.setAcceptedFileTypes(".jpg", ".jpeg", ".tif", ".tiff", ".png", ".gif", ".bmp", ".svg", ".pdf", ".mov", ".mpg", ".mpeg", ".mp3", ".mp4", ".avi", ".txt", ".eml", ".webp", ".heic", ".heif", ".hevc", ".csv");
        upload.addFileRejectedListener(fileRejectedEvent -> {
            String extension = fileRejectedEvent.getFileName().substring(fileRejectedEvent.getFileName().lastIndexOf('.') + 1);
            NotificationUtil.error("Der Dateityp \"" + extension + "\" ist nicht erlaubt.");
        });

        upload.setMaxFileSize(1_000_000);
        UploadI18N i18n = new UploadI18N();
        i18n.setError(new UploadI18N.Error()
                .setFileIsTooBig("Die Datei überschreitet die erlaubte Größe von 1 MB.")
                .setTooManyFiles("Zu viele Dateien.")
                .setIncorrectFileType("Ungültiger Dateityp.")
        );
        upload.setI18n(i18n);

As mentioned in the JavaDoc, the file size is only checked on the client, so the upload never happens. Instead, the component fires a FileRejectedEvent, which you can listen to from the server side. The error message you specified in the I18N object will be in the errorMessage property of that event.

1 Like

Thank you, in my case i needed to add spring.servlet.multipart.enabled=false
to my application.properties. Before it was 20MB allowed, so it looks like this settings override the value which is set via setMaxFileSize

There is a ticket about it: No feedback whatsoever when maxFileSize is exceeded · Issue #1665 · vaadin/flow-components · GitHub or Upload component doesn't fire failed events when uploading "too big files" · Issue #13770 · vaadin/flow · GitHub

The main issue is that the error is swallowed so it’s hard for the developer to notice.