繁体   English   中英

Spring MVC文件上传-验证

[英]Spring MVC File upload - Validation

我从那里将文件上传到我的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;
}

库:

@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 ...)。 春天怎么办?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM