Home > Blockchain >  Spring: DTO file size validation
Spring: DTO file size validation

Time:12-30

Consider two controller endpoint methods:

@RestController
public class MyController {

  @PostMapping("/foo")
  public ResponseEntity<?> foo(@Valid @RequestBody FooDto dto) {
    // ..
  }

  @PostMapping("/bar")
  public ResponseEntity<?> bar(@Valid @RequestBody BarDto dto) {
    // ..
  }
}

Actual dtos contain the multipart object, and are defined as:

class FooDto {

  @NotNull
  private MultipartFile file;

  @Size(min 2, max 40)
  private String name;
}

and similarly for BarDto of course.


Currently, the max file size is defined globally in Spring properties as:

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

In an ideal scenario, I want to control each individual dto max file size from the properties, e.g. as:

foo-dto.max-size=10MB
bar-dto.max-size=500MB

In a less idea scenario, I would like to control the size from the inside of the dto classes, e.g.:

class BarDto {

  @FileSize(max = '500MB') // <-- something like this
  @NotNull
  private MultipartFile file;

  // ..
}

Any tips on how can I achieve that? Are there existing annotations for file validation, compatible with Spring?

CodePudding user response:

You can create your own annotation for example SizeConstraint and Validator by implementing ConstraintValidator<SizeConstraint, String>. There you can validate any parameters including the size of MultiPartFile

see moree here

  • Related