Spring MVC 文件上传 - 验证

Fab*_*urz 4 java spring file-upload spring-mvc

我有一个从哪里上传文件到我的 Spring API。

控制器:

@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;
}
Run Code Online (Sandbox Code Playgroud)

存储库:

@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;
}
Run Code Online (Sandbox Code Playgroud)

我想验证一下,用户只能上传某些文件类型(pdf/doc/docx...)。如何在 Spring 中做到这一点?

Sha*_*ggy 10

您可以只检查您设置的已知列表:

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

稍后在代码中(您要验证的地方)断开文件扩展名并检查它是否在列表中:

@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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 有道理——但要像“攻击者”一样思考。如果你只是改变文件结尾怎么办? (4认同)