Apache Commons logo Commons FileUpload

Using FileUpload

Your application should detect whether or not FileUpload should be invoked, based on the HTTP method and the content type of the request.

Assuming that you have decided that FileUpload should be invoked, you might write the following code to handle a file upload request:

DiskFileItemFactory factory = DiskFileItemFactory.builder()
  // Set upload parameters
  .setBufferSize(MAX_MEMORY_SIZE)
  .setPath(Paths.get(TEMP_DIR))
  .get();

// Create a new file upload handler
JakartaServletDiskFileUpload upload = new JakartaServletDiskFileUpload(factory);
upload.setSizeMax(MAX_UPLOAD_SIZE);

// Parse the request
List<DiskFileItem> items = upload.parseRequest(request);

// Process the uploaded fields
for (DiskFileItem item :items) {
    if (item.isFormField()) {
        processTextParameter(request, item);
    } else {
        processFileParameter(request, item);
    }
}