According to OWASP standards, it is recommended validate the file type of the uploaded file. So whenever we create a controller to upload a file, it is recommended to check the file type of the uploaded file.

Currently i am check the content type by doing,

private static final List<String> contentTypes = Arrays.asList("image/png", "image/jpeg", "image/gif");

public boolean isFileValid(MultipartFile file) {
    String fileContentType = file.getContentType();
    if(contentTypes.contains(fileContentType)) {
        // Continue upload logic
    } else {
        // Handle error logic
    }
}

It would be easier to check the content type if we have an annotation for it. Like below,

@RequestMapping(value = "/file_upload", method = RequestMethod.POST)
 public ResponseEntity<String> createIssue(@RequestParam(value = "id") int id, @MultiPartFile(fileExtension={"jpg","png","gif"}) @RequestParam(value = "file") MultipartFile image){
       //Some Logic
}

It would be helpful if we have an annotation @MultiPartFile(fileExtension="") to check the uploaded file type.

Comment From: rwinch

Thanks for the suggestion.

If Spring added something like this, I think it would make more sense in Spring Framework. What are your thoughts on such a feature @rstoyanchev?

Comment From: rstoyanchev

We are trying to get away from file extensions. As far as the content type, we'd have to treat that as a mismatch in mappings which isn't the same as a validation error. Creating your own custom annotation backed by a HandlerMethodArgumentResolver with validation or any semantics you'd like might be the best way to go.

Comment From: rwinch

Thanks @rstoyanchev

@sulthan309 I'm closing this in favor of creating your own HandlerMethodArgumentResolver as mentioned above https://github.com/spring-projects/spring-security/issues/8415#issuecomment-616672702