spring boot 文件上传格式限制

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

原创文章,作者:6024010,如若转载,请注明出处:https://blog.ytso.com/243940.html

(0)
上一篇 2022年4月11日
下一篇 2022年4月11日

相关推荐

发表回复

登录后才能评论