i want to upload images added by admin(add category) into folder in project directory but i try to do so with the help of controller but it throws Unhandled exception type 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";
}
New contributor
Khushi Saraswat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1