Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC File upload - Validation

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?

like image 887
Fabian Lurz Avatar asked Mar 04 '16 18:03

Fabian Lurz


1 Answers

You could just check a known list that you set:

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

And later in the code (where you want to validate) break off the file extension and check if it is in the list:

@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
    }
}
like image 156
Shaggy Avatar answered Nov 17 '22 00:11

Shaggy