繁体   English   中英

Spring Boot 使用 thymeleaf 上传文件(图片)

[英]Spring boot upload file (image) using thymeleaf

我想上传一张图片,但我一直收到错误消息

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]]

我的控制器类

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

我在其中应用业务逻辑的服务类。 我不明白为什么这会引发错误。 我的意思是我有正确的文件路径并连接了 id 以使每个图像都是唯一的。

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

    }

我的 HTML 类

<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 不匹配

暂无
暂无

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

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