How to check file type, upload size in the Rest section in Spring?

I am trying to implement file upload using spring and Rest. That's what I did so far

@RestController @RequestMapping("/rest/upload") public class ProfileImageUploadController { @Autowired ImageValidator imageValidator; @RequestMapping(value="/{userId}/image", method=RequestMethod.POST) public @ResponseBody String handleFileUpload( @PathVariable("userId") Integer userId, @ModelAttribute("image") SingleImageFile image, BindingResult result){ MultipartFile file = image.getFile(); imageValidator.validate(file, result); if(!result.hasErrors()){ String name = file.getOriginalFilename(); try{ file.transferTo(new File("/home/maclein/Desktop/"+name)); return "You have successfully uploaded " + name + "!"; }catch(Exception e){ return "You have failed to upload " + name + " => " + e.getMessage(); } } else { return result.getFieldErrors().toString(); } } } 

Here is my ImageValidator

 @Component public class ImageValidator implements Validator { @Override public boolean supports(Class<?> arg0) { // TODO Auto-generated method stub return false; } @Override public void validate(Object uploadedFile, Errors error) { MultipartFile file = (MultipartFile) uploadedFile; if(file.isEmpty() || file.getSize()==0) error.rejectValue("file", "Please select a file"); if(!(file.getContentType().toLowerCase().equals("image/jpg") || file.getContentType().toLowerCase().equals("image/jpeg") || file.getContentType().toLowerCase().equals("image/png"))){ error.rejectValue("file", "jpg/png file types are only supported"); } } } 

But when testing through the postman, it shows an error if the file is pdf, but in a strange way. Below is a string representation of the error

"[Field error in the image object in the file field: rejected value [ org.springframework.web.multipart.commons.CommonsMultipartFile@3 fc04a65]; codes [jpg / png file types are supported only .image.file, only jpg / png file types are supported. Only files are supported file types, jpg / png.org.springframework.web.multipart.MultipartFile files, only jpg / png file types; arguments []; default message [null]] "

I cannot understand why the length of the error list is 4. My motive is to show the error in json if it is not acknowledged.

If there is a standard way to do such a check? I am new to spring and rest. So, someone, please show me a way to achieve the goal.

+5
source share
1 answer
  protected List<String> extractErrorMessages(BindingResult result) { List<String> errorMessages = new ArrayList<>(); for (Object object : result.getAllErrors()) { if (object instanceof FieldError) { FieldError fieldError = (FieldError) object; errorMessages.add(fieldError.getCode()); } } return errorMessages; } 

Take a look at the fieldError methods, maybe in your case you should use getField

+1
source

All Articles