Interface UploadHandler

All Superinterfaces:
ElementRequestHandler, Serializable
All Known Implementing Classes:
AbstractFileUploadHandler, AbstractUploadHandler, FileUploadHandler, InMemoryUploadHandler, TemporaryFileUploadHandler
Functional Interface:
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

@FunctionalInterface public interface UploadHandler extends ElementRequestHandler
Provides a flexible high-level abstraction for implementing file and arbitrary content uploads from client to server in Vaadin applications.

This interface can be implemented in two ways:

  • By creating a lambda expression that implements the handleUploadRequest(UploadEvent) method
  • By creating a child or anonymous class that implements this interface

The interface provides several factory methods for common upload scenarios:

Example:
 UploadHandler.inMemory((metadata, bytes) -> {
     // validate and save data
 });
 
All factory methods have overloads that allow adding a transfer progress listener:
 UploadHandler.toFile((metadata, file) -> {
     // validate and save file
 }, filename -> new File("/path/to/file", filename),
         new TransferProgressListener() {
             @Override
             public void onComplete(TransferContext context,
                     long transferredBytes) {
                 // show notification about file upload completion
             }
         });
 

You can use a lambda expression to handle uploads directly:

 UploadHandler handler = event -> {
     var name = event.getContentType();
     var size = event.getFileSize();
     // validate file
     try (InputStream inputStream = event.getInputStream()) {
         // process input stream
     }
 };
 

An upload is received independently of the owning component's lifecycle. The owner's attached, visible, enabled and inert state is checked when the upload request is received, but not while the upload is being received. Once handling has started, detaching the owner component, navigating to another view or closing the browser tab does not abort the transfer on the server.

A UI that is closed while an upload for it is ongoing is kept attached to its session until the upload has been handled, so that transfer progress listeners and the callbacks of the factory methods above are still run even though there is no client left to receive the UI changes.

An upload does not, however, outlive its session: if the session is invalidated, either explicitly or by timing out, an ongoing upload is terminated. The input stream of the upload stops providing content and throws an IOException instead, so the upload callback is not run and a partially received file is discarded. An application with long-lived uploads that should survive can keep the session alive while the upload is ongoing, or receive the upload through a servlet of its own that is not tied to a UI and a session.

Since:
24.8
  • Method Details

    • handleUploadRequest

      void handleUploadRequest(UploadEvent event) throws IOException
      Method that is called when the client wants to upload data to the url stored for this specific handler registration.

      After upload of all files is done the method responseHandled(UploadResult) will be called.

      Parameters:
      event - upload event containing the necessary data for getting the request
      Throws:
      IOException - if an error occurs during upload
    • responseHandled

      default void responseHandled(UploadResult result)
      Method called by framework when handleUploadRequest(UploadEvent) methods have been called for all files.

      This method sets the HTTP response return codes and writes JSON responses for rejected files:

      • 200 OK - all files accepted
      • 422 Unprocessable Entity - all files rejected (with JSON body)
      • 207 Multi-Status - some files accepted, some rejected (with JSON body)
      • 500 Internal Server Error - exception occurred

      If you want custom exception handling and to set the return code, implement this method and overwrite the default functionality.

      Parameters:
      result - the result of the upload operation containing success status, response object, any exception that occurred, and lists of accepted/rejected files
      Since:
      25.0
    • handleRequest

      default void handleRequest(VaadinRequest request, VaadinResponse response, VaadinSession session, Element owner) throws IOException
      Description copied from interface: ElementRequestHandler
      Request handler callback for handing client-server or server-client data transfer scoped to a specific (owner) element. Note: when handling requests via this API, you need to take care of typical stream handling issues, e.g. exceptions yourself. However, you do not need to close the stream yourself, Flow will handle that for you when needed.

      Note: the owner element's attached, visible, enabled and inert state is checked before this method is called, but not while it is running. A request that has already been passed to this method is therefore served to the end even if the owner element is detached, hidden or disabled in the meantime.

      Note: the request is terminated if the session is invalidated while it is being served. The streams of the given request and response then refuse to transfer any more bytes and throw an IOException instead, so a handler that reads or writes through some other means should stop on its own account when the session is no longer valid.

      Specified by:
      handleRequest in interface ElementRequestHandler
      Parameters:
      request - VaadinRequest request to handle
      response - VaadinResponse response to handle
      session - VaadinSession current VaadinSession
      owner - Element owner element
      Throws:
      IOException - if an IO error occurred during data transfer
    • getRequestSizeMax

      default long getRequestSizeMax()
      The maximum allowed size of a complete request, as opposed to getFileSizeMax(). Only targets stream multipart uploads.

      The default value of -1 indicates, that there is no limit.

      Returns:
      The maximum allowed size, in bytes
    • getFileSizeMax

      default long getFileSizeMax()
      The maximum allowed size of a single uploaded file, as opposed to getRequestSizeMax(). Only targets stream multipart uploads.

      The default value of -1 indicates, that there is no limit.

      Returns:
      Maximum size of a single uploaded file, in bytes
    • getFileCountMax

      default long getFileCountMax()
      The maximum number of files allowed per request. Only targets stream multipart uploads.

      Default is 10000.

      Returns:
      the maximum number of files allowed, -1 means no limit
    • toFile

      static FileUploadHandler toFile(FileUploadCallback successCallback, FileFactory fileFactory)
      Generate an upload handler for storing upload stream into a file.
      Parameters:
      successCallback - consumer to be called when upload successfully completes
      fileFactory - factory for generating file to write to
      Returns:
      file upload handler
    • toFile

      static FileUploadHandler toFile(FileUploadCallback successCallback, FileFactory fileFactory, TransferProgressListener listener)
      Generate an upload handler for storing upload stream into a file with progress handling.
      Parameters:
      successCallback - consumer to be called when upload successfully completes
      fileFactory - factory for generating file to write to
      listener - listener for transfer progress events
      Returns:
      file upload handler instance with progress listener
    • toTempFile

      static TemporaryFileUploadHandler toTempFile(FileUploadCallback successCallback)
      Generate an upload handler for storing upload stream into a temporary file.
      Parameters:
      successCallback - consumer to be called when upload successfully completes
      Returns:
      temporary file upload handler instance
    • toTempFile

      static TemporaryFileUploadHandler toTempFile(FileUploadCallback successCallback, TransferProgressListener listener)
      Generate an upload handler for storing upload stream into a temporary file with progress handling.
      Parameters:
      successCallback - consumer to be called when upload successfully completes
      listener - listener for transfer progress events
      Returns:
      temporary file upload handler instance with progress listener
    • inMemory

      static InMemoryUploadHandler inMemory(InMemoryUploadCallback successCallback)
      Generate upload handler for storing download into in-memory byte[].
      Parameters:
      successCallback - consumer to be called when upload successfully completes
      Returns:
      in-memory upload handler
    • inMemory

      static InMemoryUploadHandler inMemory(InMemoryUploadCallback successCallback, TransferProgressListener listener)
      Generate upload handler for storing download into in-memory byte[] with progress handling.
      Parameters:
      successCallback - consumer to be called when upload successfully completes
      listener - listener for transfer progress events
      Returns:
      in-memory upload handler with progress listener