Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring MVC文件上载-验证_Java_Spring_Spring Mvc_File Upload - Fatal编程技术网

Java Spring MVC文件上载-验证

Java Spring MVC文件上载-验证,java,spring,spring-mvc,file-upload,Java,Spring,Spring Mvc,File Upload,我有一个将文件上传到SpringAPI的窗口 控制器: @RequestMapping(value = "/upload", method = RequestMethod.POST) public JSONObject handleCVUpload(@RequestParam("file") MultipartFile file,HttpServletRequest request) { User user=userService.findUserByAccessToken(new Ac

我有一个将文件上传到SpringAPI的窗口

控制器:

@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");

MultipartFile
实例上调用
getContentType
,查看它是什么..这安全吗?难道你不能伪造一个ContentType吗?你可以使用ApacheTika查看文件的实际内容,看看它是否合法——但要像“攻击者”一样思考。如果您只是更改文件的结尾怎么办?您正在使用MultipartFile。。。它具有getContentType()方法,该方法将返回内容类型,您可以对照已批准的列表进行检查。下面是其中一些的列表。。。
@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
    }
}