Arek
Arek

Reputation: 53

Vaadin upload component - File added event

Is there a way to detect that file has been added to the upload component? There is a file-remove to detect if the file is removed, can we somehow detect if a file is added?

Simplify scenario: When a File is added display a simple notification.

Upvotes: 4

Views: 594

Answers (1)

Oliver
Oliver

Reputation: 1655

After reviewing https://github.com/vaadin/vaadin-upload/blob/master/src/vaadin-upload.html, this is not possible with the vaadin-upload element as is.

But you can extend UploadElement!

UploadElement has a function named _addFile, which is called whenever a file is added. You just have to confirm the same predicates (which is a bit inefficient, but is what it is), and if the file is to be added, fire a new custom event.

custom-vaadin-upload.js:

import {UploadElement} from '@vaadin/vaadin-upload/src/vaadin-upload';

class CustomUploadElement extends UploadElement {

  static get is() {
    return 'custom-vaadin-upload';
  }

  constructor() {
    super();
  }

  _addFile(file) {
    const fileExt = file.name.match(/\.[^\.]*$|$/)[0];
    const re = new RegExp('^(' + this.accept.replace(/[, ]+/g, '|').replace(/\/\*/g, '/.*') + ')$', 'i');

    if(
        !this.maxFilesReached
        && !(this.maxFileSize >= 0 && file.size > this.maxFileSize)
        && !(this.accept && !(re.test(file.type) || re.test(fileExt)))
    ) {
      this.dispatchEvent(new CustomEvent('file-accept', {detail: {file}}));
    }

    super._addFile(file);
  }

}

customElements.define(CustomUploadElement.is, CustomUploadElement);

CustomUpload.java:

@Tag("custom-vaadin-upload")
@JsModule("./src/custom-vaadin-upload.js")
public class CustomUpload extends Upload {

  public CustomUpload() {
    super();
  }

  public CustomUpload(final Receiver receiver) {
    super(receiver);
  }

  public Registration addFileAcceptListener(final ComponentEventListener<FileAcceptEvent> listener) {
    return addListener(FileAcceptEvent.class, listener);
  }

  @DomEvent("file-accept")
  public static class FileAcceptEvent extends ComponentEvent<CustomUpload> {

    private final JsonObject detail;

    private final JsonObject detailFile;

    public FileAcceptEvent(final CustomUpload source, final boolean fromClient,
        @EventData("event.detail") final JsonObject detail,
        @EventData("event.detail.file") final JsonObject detailFile) {
      super(source, fromClient);

      this.detail = detail;
      this.detailFile = detailFile;
    }

    public final JsonObject getDetail() {
      return detail;
    }

    public final JsonObject getDetailFile() {
      return detailFile;
    }

  }

}

Example usage:

final MemoryBuffer buffer = new MemoryBuffer();
final CustomUpload upload = new CustomUpload(buffer);

upload.addFileAcceptListener(System.out::println);

You can read more about extending client-side elements here and mapping DOM events to Java here.

Upvotes: 5

Related Questions