9

我正在尝试使用 spring 和 Rest 实现文件上传。这是我到目前为止所做的

@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();
       }
   }
}

这是我的 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");
       }
   }
}

但是在通过邮递员进行测试时,如果文件是 pdf 但以一种奇怪的方式显示错误。这是错误的字符串表示形式

“[字段'文件'上的对象'图像'中的字段错误:拒绝值[org.springframework.web.multipart.commons.CommonsMultipartFile@3fc04a65];代码[仅支持jpg/png文件类型.image.file,jpg/ png 文件类型仅支持.file,jpg/png 文件类型仅支持.org.springframework.web.multipart.MultipartFile,jpg/png 文件类型仅支持]; 参数 []; 默认消息 [null]]"

我不明白为什么错误列表长度为 4。我的动机是在 json 中显示错误,如果它没有经过验证。

如果有任何标准方法来进行这种验证?我是春天和休息的新手。所以有人请告诉我实现目标的方法。

4

1 回答 1

1
 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;
    }

看看 fieldError 方法,可能在你的情况下你应该使用 getField

于 2015-08-23T04:52:21.110 回答