2016-03-04 81 views
1

我有一個從哪裏上傳文件到我的Spring API。Spring MVC文件上傳 - 驗證

控制器:

@RequestMapping(value = "/upload", method = RequestMethod.POST) 
public JSONObject handleCVUpload(@RequestParam("file") MultipartFile file,HttpServletRequest request) { 
    User user=userService.findUserByAccessToken(new AccessTokenFromRequest().getAccessToken(request)); 
    JSONObject messageJson = new JSONObject(); 
    messageJson.put("success", userService.uploadCV(user, file)); 
    return messageJson; 
} 

庫:

@Override 
public boolean uploadCV(User user, MultipartFile file) { 
    boolean uploadsuccess = false; 
    String fileName = user.getUserId() + "_" + user.getName(); 
    if (!file.isEmpty()) { 
     try { 
      String type = file.getOriginalFilename().split("\\.")[1]; 
      BufferedOutputStream stream = new BufferedOutputStream(
        new FileOutputStream(new File("/data/" + fileName + "." + type))); 
      FileCopyUtils.copy(file.getInputStream(), stream); 
      stream.close();    
      uploadsuccess = true; 
     } catch (Exception e) { 
      System.err.println(e); 
      uploadsuccess = false; 
     } 
    } 
    return uploadsuccess; 
} 

我想驗證,用戶只能上傳特定類型的文件(PDF/DOC/DOCX ...)。 如何在Spring中做到這一點?

+0

在'MultipartFile'實例上調用'getContentType'並查看它是什麼.. –

+0

這是安全的嗎?你不能只是僞造一個ContentType? –

+0

您可以使用Apache Tika查看文件的實際內容並查看它是否合法 –

回答

2

你可以只檢查是否設置一個已知的名單:

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

後來分手文件擴展名,並檢查它是否在列表中:

@Override 
public boolean uploadCV(User user, MultipartFile file) { 
    String fileContentType = file.getContentType(); 
    if(contentTypes.contains(fileContentType)) { 
     // You have the correct extension 
     // rest of your code here 
    } else { 
     // Handle error of not correct extension 
    } 
} 
+1

有意義 - 但像「攻擊者」一樣思考。如果你只是改變文件結束呢? –

+1

您正在使用MultipartFile ...,它具有方法getContentType(),它將返回您可以檢查您的允許列表的內容類型。以下是其中一些列表... http://www.java2s.com/Code/Java/Network-Protocol/MapfileextensionstoMIMEtypesBasedontheApachemimetypesfile.htm – Shaggy