spring boot 文件上传格式限制

位置:首页>文章>详情   分类:Java教程   阅读(1396)   2023-03-28 11:29:14
spring boot文件格式限制
做项目的时候经常遇到需要文件上传和限制文件上传的格式,文件格式虽然前端js能限制一次。但是作为稳定的后端服务,还是需要再次校验保证格式接口的稳定性。

首先创建一个集合,用于存放那些文件格式支持上传的,这里主要是以文件名后缀方式来判断
List<String> supportFileFormats =new ArrayList<>(Arrays.asList("doc,docx,xls,xlsx,ppt,pptx,pdf,jpg,jpeg,png,txt,wmv,mp4".split(",")));

编写一个方法,接受文件名并校验格式
 
private boolean checkFormats(String fileFullName){
   String suffix = fileFullName.substring(fileFullName.lastIndexOf(".") + 1).toLowerCase();
   return supportFileFormats.stream().anyMatch(suffix::contains);
}

调用格式检测方法
    @PostMapping("upload")
    @ResponseBody
    public String upload(FileInfo info, MultipartFile file){
        System.out.println(JSON.toJSONString(info));
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);
        boolean checkFormats = checkFormats(originalFilename);
        System.out.println(checkFormats);
        return "success";
    }
    
地址:https://www.leftso.com/article/977.html