0

I need to limit the number of MultipartFiles sent to Spring Rest API. The annotations from jakarta.validation.constraints don't work for List<MultipartFile> files for some reason, but they do work for lists of other objects, such as List<String> strings for example.

        @Valid
        @Size(min = 1, max = 2, message = "files.size")
        @RequestPart(name = "files")
        List<MultipartFile> files,
        @Valid
        @Size(min = 1, max = 2, message = "strings.size")
        @RequestParam(name = "strings")
        List<String> strings,

In the above example, more than 2 strings are not allowed by validation, but more than 2 files are allowed.

Please tell me how, preferably, using annotations to limit the number of files in list for the endpoint

tabool
  • 89
  • 9

1 Answers1

0

To validate the elements of a List, you'll need to implement a custom validator. You can achieve this by creating a custom validator that validates each element of the list individually. Here's an example of how you could do this using Spring's Validator interface:

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.web.multipart.MultipartFile;

@Component
public class MultipartFileListValidator implements Validator {

    private static final int MIN_SIZE = 1;
    private static final int MAX_SIZE = 2;

    @Override
    public boolean supports(Class<?> clazz) {
        return List.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        List<MultipartFile> files = (List<MultipartFile>) target;
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "files", "files.empty", "Files must not be empty");

        if (files.size() < MIN_SIZE || files.size() > MAX_SIZE) {
            errors.rejectValue("files", "files.size", "Invalid number of files");
        }

        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            if (file.isEmpty()) {
                errors.rejectValue("files[" + i + "]", "files.empty", "File must not be empty");
            }
            // Add additional checks for individual file properties if needed
        }
    }
}

@RestController
public class MyController {

    private final MultipartFileListValidator validator;

    @Autowired
    public MyController(MultipartFileListValidator validator) {
        this.validator = validator;
    }

    @PostMapping("/upload")
    public ResponseEntity<String> handleFileUpload(@RequestPart("files") @Valid List<MultipartFile> files) {
        // Your code to handle file upload
    }

    @InitBinder("files")
    protected void initBinder(WebDataBinder binder) {
        binder.addValidators(validator);
    }
}
jokernoel
  • 83
  • 4