簡體   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