Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring boot 在spring引导中将多部分文件转换为字符串失败_Spring Boot_Validation_Multipartfile - Fatal编程技术网

Spring boot 在spring引导中将多部分文件转换为字符串失败

Spring boot 在spring引导中将多部分文件转换为字符串失败,spring-boot,validation,multipartfile,Spring Boot,Validation,Multipartfile,这是错误消息: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'post' on field 'thumbnail': rejected value [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@491e3141

这是错误消息:

org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'post' on field 'thumbnail': rejected value [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@491e3141]; 
codes [typeMismatch.post.thumbnail,typeMismatch.thumbnail,typeMismatch.java.lang.String,typeMismatch]; 
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [post.thumbnail,thumbnail]; arguments []; default message [thumbnail]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.lang.String' for property 'thumbnail'; 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 'thumbnail': no matching editors or conversion strategy found]
@PostMapping(value = {"/add"}, consumes = {"multipart/form-data"})
public String addPost(@RequestParam("thumbnail") MultipartFile multipartFile, @ModelAttribute("post") 
                       PostDTO postDTO, BindingResult bindingResult, Model model)
                throws IOException {
    postValidator.validate(postDTO, bindingResult);
    if(bindingResult.hasErrors()) {
        model.addAttribute("categories", categoryService.findAll());
        return "/admin/add_post";
    }
    String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename());
    postDTO.setThumbnail(fileName);
    PostDTO savedPost = postService.save(postDTO);
    String uploadDir = "./post-thumbnails/" + savedPost.getId();
    Path uploadPath = Paths.get(uploadDir);
    if(!Files.exists(uploadPath)) {
        Files.createDirectories(uploadPath);
    }
    try {
        InputStream inputStream = multipartFile.getInputStream();
        Path filePath = uploadPath.resolve(fileName);
        Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
    }
    catch (IOException e) {
        throw new IOException("Could not save uploaded file: " + fileName);
    }
    return "redirect:/admin/list";
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{/admin/layout}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>edit page</title>
    <script src="https://cdn.ckeditor.com/4.14.1/standard/ckeditor.js"></script>
</head>
<body>
    <div layout:fragment="content">
        <div class="breadcumb">
            <p>Edit Post</p>
        </div>
        <div class="form">
            <form th:action="@{/admin/add}" th:object="${post}" method="post" enctype="multipart/form-data">
                <label>Title</label>
                <input th:field="*{title}" type="text" placeholder="Your title">
                <p class="help-block text-danger" th:if="${#fields.hasErrors('title')}" th:errors="*{title}"></p>
                <label>Description</label>
                <textarea th:field="*{shortDescription}" name="description" id="description" cols="30" rows="2" placeholder="Your description..."></textarea>
                <p class="help-block text-danger" th:if="${#fields.hasErrors('shortDescription')}" th:errors="*{shortDescription}"></p>
                <label>Content</label>
                <textarea th:field="*{content}" name="content" id="content" cols="80" rows="10" placeholder="Your content..."></textarea>
                <p class="help-block text-danger" th:if="${#fields.hasErrors('content')}" th:errors="*{content}"></p>
                <label>Thumbnail</label>
                <input type="file" name="thumbnail" id="thumbnail" accept="image/jpeg, image/png">
                <p style="color: red" th:if="${#fields.hasErrors('thumbnail')}" th:errors="*{thumbnail}"></p>
                <label>Category</label>
                <select th:field="*{categoryName}" name="category" id="category">
                    <option th:each="item: ${categories}" th:value="${item.getName()}" th:text="${item.getName()}"></option>
                </select>
                <input type="submit" value="Create">
            </form>
        </div>
        <!-- scripts start -->
        <script>
            CKEDITOR.replace('content');
        </script>
        <!-- scripts end -->
    </div>
</body>
</html>
控制器:

org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'post' on field 'thumbnail': rejected value [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@491e3141]; 
codes [typeMismatch.post.thumbnail,typeMismatch.thumbnail,typeMismatch.java.lang.String,typeMismatch]; 
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [post.thumbnail,thumbnail]; arguments []; default message [thumbnail]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.lang.String' for property 'thumbnail'; 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 'thumbnail': no matching editors or conversion strategy found]
@PostMapping(value = {"/add"}, consumes = {"multipart/form-data"})
public String addPost(@RequestParam("thumbnail") MultipartFile multipartFile, @ModelAttribute("post") 
                       PostDTO postDTO, BindingResult bindingResult, Model model)
                throws IOException {
    postValidator.validate(postDTO, bindingResult);
    if(bindingResult.hasErrors()) {
        model.addAttribute("categories", categoryService.findAll());
        return "/admin/add_post";
    }
    String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename());
    postDTO.setThumbnail(fileName);
    PostDTO savedPost = postService.save(postDTO);
    String uploadDir = "./post-thumbnails/" + savedPost.getId();
    Path uploadPath = Paths.get(uploadDir);
    if(!Files.exists(uploadPath)) {
        Files.createDirectories(uploadPath);
    }
    try {
        InputStream inputStream = multipartFile.getInputStream();
        Path filePath = uploadPath.resolve(fileName);
        Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
    }
    catch (IOException e) {
        throw new IOException("Could not save uploaded file: " + fileName);
    }
    return "redirect:/admin/list";
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{/admin/layout}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>edit page</title>
    <script src="https://cdn.ckeditor.com/4.14.1/standard/ckeditor.js"></script>
</head>
<body>
    <div layout:fragment="content">
        <div class="breadcumb">
            <p>Edit Post</p>
        </div>
        <div class="form">
            <form th:action="@{/admin/add}" th:object="${post}" method="post" enctype="multipart/form-data">
                <label>Title</label>
                <input th:field="*{title}" type="text" placeholder="Your title">
                <p class="help-block text-danger" th:if="${#fields.hasErrors('title')}" th:errors="*{title}"></p>
                <label>Description</label>
                <textarea th:field="*{shortDescription}" name="description" id="description" cols="30" rows="2" placeholder="Your description..."></textarea>
                <p class="help-block text-danger" th:if="${#fields.hasErrors('shortDescription')}" th:errors="*{shortDescription}"></p>
                <label>Content</label>
                <textarea th:field="*{content}" name="content" id="content" cols="80" rows="10" placeholder="Your content..."></textarea>
                <p class="help-block text-danger" th:if="${#fields.hasErrors('content')}" th:errors="*{content}"></p>
                <label>Thumbnail</label>
                <input type="file" name="thumbnail" id="thumbnail" accept="image/jpeg, image/png">
                <p style="color: red" th:if="${#fields.hasErrors('thumbnail')}" th:errors="*{thumbnail}"></p>
                <label>Category</label>
                <select th:field="*{categoryName}" name="category" id="category">
                    <option th:each="item: ${categories}" th:value="${item.getName()}" th:text="${item.getName()}"></option>
                </select>
                <input type="submit" value="Create">
            </form>
        </div>
        <!-- scripts start -->
        <script>
            CKEDITOR.replace('content');
        </script>
        <!-- scripts end -->
    </div>
</body>
</html>
表单html:

org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'post' on field 'thumbnail': rejected value [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@491e3141]; 
codes [typeMismatch.post.thumbnail,typeMismatch.thumbnail,typeMismatch.java.lang.String,typeMismatch]; 
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [post.thumbnail,thumbnail]; arguments []; default message [thumbnail]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.lang.String' for property 'thumbnail'; 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 'thumbnail': no matching editors or conversion strategy found]
@PostMapping(value = {"/add"}, consumes = {"multipart/form-data"})
public String addPost(@RequestParam("thumbnail") MultipartFile multipartFile, @ModelAttribute("post") 
                       PostDTO postDTO, BindingResult bindingResult, Model model)
                throws IOException {
    postValidator.validate(postDTO, bindingResult);
    if(bindingResult.hasErrors()) {
        model.addAttribute("categories", categoryService.findAll());
        return "/admin/add_post";
    }
    String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename());
    postDTO.setThumbnail(fileName);
    PostDTO savedPost = postService.save(postDTO);
    String uploadDir = "./post-thumbnails/" + savedPost.getId();
    Path uploadPath = Paths.get(uploadDir);
    if(!Files.exists(uploadPath)) {
        Files.createDirectories(uploadPath);
    }
    try {
        InputStream inputStream = multipartFile.getInputStream();
        Path filePath = uploadPath.resolve(fileName);
        Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
    }
    catch (IOException e) {
        throw new IOException("Could not save uploaded file: " + fileName);
    }
    return "redirect:/admin/list";
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{/admin/layout}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>edit page</title>
    <script src="https://cdn.ckeditor.com/4.14.1/standard/ckeditor.js"></script>
</head>
<body>
    <div layout:fragment="content">
        <div class="breadcumb">
            <p>Edit Post</p>
        </div>
        <div class="form">
            <form th:action="@{/admin/add}" th:object="${post}" method="post" enctype="multipart/form-data">
                <label>Title</label>
                <input th:field="*{title}" type="text" placeholder="Your title">
                <p class="help-block text-danger" th:if="${#fields.hasErrors('title')}" th:errors="*{title}"></p>
                <label>Description</label>
                <textarea th:field="*{shortDescription}" name="description" id="description" cols="30" rows="2" placeholder="Your description..."></textarea>
                <p class="help-block text-danger" th:if="${#fields.hasErrors('shortDescription')}" th:errors="*{shortDescription}"></p>
                <label>Content</label>
                <textarea th:field="*{content}" name="content" id="content" cols="80" rows="10" placeholder="Your content..."></textarea>
                <p class="help-block text-danger" th:if="${#fields.hasErrors('content')}" th:errors="*{content}"></p>
                <label>Thumbnail</label>
                <input type="file" name="thumbnail" id="thumbnail" accept="image/jpeg, image/png">
                <p style="color: red" th:if="${#fields.hasErrors('thumbnail')}" th:errors="*{thumbnail}"></p>
                <label>Category</label>
                <select th:field="*{categoryName}" name="category" id="category">
                    <option th:each="item: ${categories}" th:value="${item.getName()}" th:text="${item.getName()}"></option>
                </select>
                <input type="submit" value="Create">
            </form>
        </div>
        <!-- scripts start -->
        <script>
            CKEDITOR.replace('content');
        </script>
        <!-- scripts end -->
    </div>
</body>
</html>

编辑页面
编辑文章

标题

描述

内容

缩略图

类别 CKEDITOR.replace('content');