限制上传图片大小,格式为jpg 或者 png

在Constants.java中:
 public static HashMap<String, String> getPhotoTypeMap() {
  HashMap<String, String> resultMap = new HashMap<String, String>();
  resultMap.put("jpg", "");
  resultMap.put("png", "");
  return resultMap;
 } 

@RequestMapping(value = "/uploadAvatarImage", method = RequestMethod.POST)
 public String uploadAvatarImage(Model uiModel, @RequestParam("avatarImageFile") MultipartFile file) {  
  String originalFileName=file.getOriginalFilename(); 
  if (!"".equals(file.getOriginalFilename()) && file.getSize() <= Constants.SYSTEM_IMAGE_MAX_SIZE) {
   String type=originalFileName.substring(originalFileName.lastIndexOf(".")+1);
   if (!Constants.getPhotoTypeMap().containsKey(type.toLowerCase())) {
    uiModel.addAttribute("validateMessage", "The format of the image is not supported, you can only upload the format of jpg or png.");
       return showProfile(uiModel,"Y");
   }
  }
  
  if (file == null || file.getSize() <= 0) {
   uiModel.addAttribute("validateMessage", "The image size can not be zero.");
   return showProfile(uiModel,"Y");
  }
  
  if (file.getSize() > Constants.SYSTEM_IMAGE_MAX_SIZE) {
   uiModel.addAttribute("validateMessage", "The image size can not exceed 1024K.");
   return showProfile(uiModel,"Y");
  }
  
  try {
   UploadFile uploadThumbnailImage = Tools.uploadImageWithThumbnail(file, Constants.UPLOADFILE_HOMEOWNER_AVATAR_PATH, Constants.SYSTEM_THUMBNAIL_IMAGE_WIDTH, Constants.SYSTEM_THUMBNAIL_IMAGE_HEIGHT);
   
   if (uploadThumbnailImage != null) {
    User currentUser = getCurrentUser();
    
    uploadThumbnailImage.setUser(currentUser);
    uploadThumbnailImage.setCategory(Constants.UPLOADFILE_AVATAR_TYPE);
    
    uploadFileService.saveUploadImage(uploadThumbnailImage);
   }
   
  } catch (IOException e) {
   e.printStackTrace();
  }

  showProfile(uiModel,"N");
  
  return "redirect:/homeowner/profile";
 }

posted @ 2012-02-10 09:38  柠檬Cool  阅读(2848)  评论(0编辑  收藏  举报