繁体   English   中英

验证jpg和png的上传文件并保存到静态文件夹

[英]Validate uploaded file for jpg and png and save to static folder

我正在使用spring boot,我想通过表单上传图片。

它有效,但有两个问题:

1)我不知道如何验证文件以确保它是jpgpng

2)我只能上传到root文件夹,而不能上传到static文件夹,我不知道如何设置resources/static文件夹的正确路径

@PostMapping("/add")
    public String add(@Valid Product product, @RequestParam MultipartFile file, BindingResult bindingResult,
            RedirectAttributes redirectAttributes, Model model) {
...

try {
            byte[] bytes = file.getBytes(); // how to validate this?
            Path path = Paths.get( file.getOriginalFilename()); // how to set path here?
            Files.write(path, bytes);

            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + file.getOriginalFilename() + "'");

        } catch (IOException e) {
            System.out.println("!!!!!!!!!!!!! Image uploaded problem !!!!!!!!!!!!!!");
            e.printStackTrace();
        }

...
}

获取文件扩展名

String extension = FilenameUtils.getExtension(file.getOriginalFilename());

路径

 InputStream in = file.getInputStream();
 File destination = new File("/some-location/" + file.getOriginalFilename());
 FileUtils.copyInputStreamToFile(in, destination);

暂无
暂无

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

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