Limit File Size with Bean Shell

Introduction 

This guide shows how to use a Bean Shell validator to ensure that the total size of multiple uploaded files does not exceed a specified limit. This approach checks both individual file sizes and the cumulative size of all files.

Example scenarios

  • Exceeding Limit:
    If a file exceeds the 5 MB limit, the validator will trigger an error.

  • Total Size Exceeding Limit:
    If the total size of multiple files exceeds 5 MB, even if each file is below the limit, the validator will activate.

Implementation

To configure the Bean Shell validator for the file upload element:

  1. Access the File Upload Element in your form and select the Bean Shell Validator.
  2. Insert the following Validation Code into the script section of the Bean Shell validator.
    import org.joget.apps.form.service.FormUtil;
    import org.joget.commons.util.FileManager;
     
    boolean result = true;
    String[] values = FormUtil.getElementPropertyValues(element, formData);
    long totalSize = 0;
    long maxSize = 5000000;
    String errorMessage = "";
     
    for (String value : values) {
        File file = FileManager.getFileByPath(value);
        if (file != null) {
            totalSize += file.length();
            errorMessage += file.getName() + "(" + file.length()/1048576 + ") " + " | ";
        }
    }
    if (totalSize > maxSize) {
        String id = FormUtil.getElementParameterName(element);
        formData.addFormError(id, "Max size(MB) (" + maxSize/1000000 + ") | " + errorMessage);
        result = false;
    }
     
    return result;

Related documentation 

Created by Julieth Last modified by Aadrian on Dec 13, 2024