Spring MVC File upload - Validation

时间:2016-03-04 18:01:48

标签: java spring spring-mvc file-upload

I have a from where i upload files to my Spring API.

Controller:

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

Repository:

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

I would like to validate, that users can only upload certain file types (pdf/doc/docx...). How to do that in Spring?

1 个答案:

答案 0 :(得分: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
    }
}