有人能帮帮我吗?我在使用多部分的Rest控制器中验证文件大小限制的问题,但它不起作用。我已经得到了multipart的大小,并添加了一些if语句来消息文件的超出限制,但它不起作用。
@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);
}
}
如果您要使用SpringBoot,您可以通过属性application.yml
或application.properties
来实现,例如:
servlet:
multipart:
max-file-size: 5MB
max-request-size: 120MB
enabled: true
还可以创建一个自定义验证器:
@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;
}
}
和您自己的验证注释:
@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 {};
}
用新的注释创建请求类型:
@AllArgsConstructor
@Getter
public class Request {
@MultipartFileSizeValid
private final MultipartFile file;
}
并在控制器中添加@Valid:
@RequestMapping(value = "/importCsvFile", method = RequestMethod.POST)
public ResponseEntity<?> importCsvFile(@Valid Request request) {...}
并在控制器中使用@Validated
注释,有关应用自定义验证注释的更多信息,请参阅此处