简体   繁体   中英

Validation for File Size Limit Multipart using Spring Java

Can someone help me? I have a issue in validation of file size limit in Rest controller using multipart but it does not work. I already get the size of multipart and add some if statement to message the exceed limit of the file but its not working.

    @RequestMapping(value = "/importCsvFile", method = RequestMethod.POST)
    public ResponseEntity<?> importCsvFile(MultipartFile inputFile) throws Exception {

        if (inputFile == null || inputFile.isEmpty()) {

            return new ResponseEntity<>("Please insert a CSV file.", HttpStatus.NOT_FOUND);

        }
        if (!inputFile.getContentType().equals("application/vnd.ms-excel")) {

            return new ResponseEntity<>("Upload CSV file only.", HttpStatus.NOT_ACCEPTABLE);
        }
        if (inputFile.getSize() > 1048576) { **====> File size limit**

            return new ResponseEntity<>("File too Large.", HttpStatus.NOT_ACCEPTABLE);
        } 
        else {

            List<Object> items = objectSrvc.importCsvFile(inputFile.getInputStream());

            if (items == null) {
                return new ResponseEntity<List<Object>>(HttpStatus.NO_CONTENT);
            }
            return new ResponseEntity<List<Object>>(items, HttpStatus.OK);
        }
    }

If you'll use SpringBoot you can do it by property application.yml or application.properties , for example:

  servlet:
    multipart:
      max-file-size: 5MB
      max-request-size: 120MB
      enabled: true

Also, you can create a custom validator:

@Component
public class MultipartFileSizeValidator implements ConstraintValidator<MultipartFileSizeValid, List<?>> {

    private static final String ERROR_MESSAGE = "File too Large.";

    private static final long FILE_SIZE = 1048576L;

    @Override
    public boolean isValid(final List<?> value, final ConstraintValidatorContext context) {        context.buildConstraintViolationWithTemplate(ERROR_MESSAGE).addConstraintViolation();
        return inputFile.getSize() > FILE_SIZE;
    }
}

and your own annotation for validation:

@Target({FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = MultipartFileSizeValidator.class)
public @interface MultipartFileSizeValid {

    String message() default "DEFAULT_ERROR_MESSAGE";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

Create request type with new annotation:

@AllArgsConstructor
@Getter
public class Request {

@MultipartFileSizeValid
private final MultipartFile file;

}

and add @Valid into the controller:

   @RequestMapping(value = "/importCsvFile", method = RequestMethod.POST)
    public ResponseEntity<?> importCsvFile(@Valid Request request) {...}

And use this annotation with @Validated in your controller, for more info about applying the custom validation annotation see 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