文件上传到 ClassPathResource - IOException

问题描述 投票:0回答:1

我想将管理员添加的图像(添加类别)上传到项目目录中的文件夹中,但我尝试在控制器的帮助下执行此操作,但它会抛出未处理的异常类型 IOException

@PostMapping("/saveCategory")
    public String saveCategory(@ModelAttribute Category category, @RequestParam("file") MultipartFile file,
            HttpSession session) {
        System.out.println(file.getOriginalFilename());
        String imageName = file != null ? file.getOriginalFilename() : "default.jpg";
        category.setImageName(imageName);

        Boolean existCategory = categoryService.existCategory(category.getName());
        if (existCategory) {
            session.setAttribute("errorMsg", "Category name already exist");
        } else {
            Category saveCategory = categoryService.saveCategory(category);
            if (!ObjectUtils.isEmpty(saveCategory)) {
                session.setAttribute("errorMsg", "Not saved ! internally server error");
            } else {

                // first of all get the path onto which u want to upload the file.

    File saveFile = new ClassPathResource("static/img").getFile();

    Path path = Paths.get(saveFile.getAbsolutePath() + File.separator + "category_img" + File.separator+ file.getOriginalFilename());

                // System.out.println(path);
Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);

                session.setAttribute("succMsg", "Saved successfully");

            }
        }

        return "redirect:/admin/Category";
    }
html spring bootstrap-4 thymeleaf
1个回答
0
投票

您无法写入 ClasspPathResource。

更换

File saveFile = new ClassPathResource("static/img").getFile();

Path path = Paths.get(saveFile.getAbsolutePath() + File.separator + "category_img" + File.separator+ file.getOriginalFilename());

Path path = Paths.get("fullpath/to/folder" + File.separator + "category_img" + File.separator+ file.getOriginalFilename());

您可能应该将

"fullpath/to/folder"
作为配置值,并且它必须可以从运行 java 的服务器访问。

© www.soinside.com 2019 - 2024. All rights reserved.