2016-03-04 59 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