简体   繁体   中英

Spring: DTO file size validation

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, eg 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, eg:

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM