Joh*_*ein 7 java rest spring spring-mvc spring-restcontroller
我正在尝试使用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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当通过邮递员进行测试时,如果文件是pdf但是以奇怪的方式显示错误.这是错误的字符串表示
"[字段'文件'上的对象'图像'中的字段错误:被拒绝的值[org.springframework.web.multipart.commons.CommonsMultipartFile@3fc04a65];代码[jpg/png文件类型仅受支持.image.file,jpg/png文件类型仅支持.file,jpg/png文件类型仅支持..org.springframework.web.multipart.MultipartFile,仅支持jpg/png文件类型]; arguments [];默认消息[null]]"
我无法理解为什么错误列表长度为4.我的动机是在json中显示错误,如果它没有经过验证.
如果有任何标准方法可以进行此类验证?我是春天和休息的新手.所以有人请告诉我实现目标的方法.
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;
}
Run Code Online (Sandbox Code Playgroud)
看看 fieldError 方法,可能在你的情况下你应该使用 getField
| 归档时间: |
|
| 查看次数: |
8068 次 |
| 最近记录: |