I want to upload an image but I keep getting an error
Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors<EOL>Field error in object 'product' on field 'imageName': rejected value [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@526bc09]; codes [typeMismatch.product.imageName,typeMismatch.imageName,typeMismatch.java.lang.String,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [product.imageName,imageName]; arguments []; default message [imageName]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.lang.String' for property 'imageName'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.lang.String' for property 'imageName': no matching editors or conversion strategy found]]
My Controller class
@GetMapping("/showNewProductForm")
public String showNewProductForm(Model model) {
model.addAttribute("saved", new Product());
return "showNewProductForm";
}
@PostMapping("/showNewProductForm")
public String addAProduct(@ModelAttribute Product product,
Model model,
@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) throws IOException {
model.addAttribute("saved", product);
productService.saveProduct(product, file);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + product.getName() + "!");
return "redirect:/showNewProductForm";
}
My Service class where I am applying the business logic. I do not understand why this is throwing an error. I mean I have the correct file path and concatinated the id to make each image unique.
public void saveProduct(Product product, MultipartFile file) throws IOException {
// 1. Check if image is not empty
//2. If file is empty
//3. The user exists in the database
Optional<Product> productByName = productRepository.findProductByName(product.getName());
if (productByName.isPresent()) {
System.out.println("Product with name " + product.getName() + " already exist");
}
String fileName = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));
product.setImageName(fileName);
Product savedProduct = productRepository.save(product);
String uploadDirectory = "src/main/resources/static/photos/" + savedProduct.getId();
saveFile(uploadDirectory, fileName, file);
}
public void saveFile(String uploadDirectory,
String fileName,
MultipartFile file) throws IOException {
Path path = Paths.get(uploadDirectory);
if (!Files.exists(path)) {
Files.createDirectories(path);
}
try (InputStream inputStream = file.getInputStream()) {
Path filePath = path.resolve(fileName);
Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ioe) {
throw new IOException("Could not save image file: " + fileName, ioe);
}
}
My Html class
<form action="#" th:action="@{/showNewProductForm}" th:object="${saved}" method="post" enctype="multipart/form-data">
<p>Name: <input type="text" th:field="*{name}" /></p>
<p>Category: <input type="text" th:field="*{category}" /></p>
<!-- th:field="*{imageName}" -->
<p>Image: <input name="image" type="file" accept="image/png, image/jpg, image/jpeg" th:field="*{imageName}"/></p>
<p>Description: <input type="text" th:field="*{description}" /></p>
<button type="submit" value="Submit">Save Product</button>
</form>
为了解决这个错误,我不得不更改 HTML 中的 Image,因为它与控制器类中的 @RequestParam 不匹配
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.