在春季启动中无法成功上传图片

时间:2019-12-04 16:15:13

标签: java spring spring-boot file spring-mvc

我有一个带有图像的数据提交表单。但是,当我单击“提交”按钮时,出现以下错误:

  

org.springframework.validation.BindException:org.springframework.validation.BeanPropertyBindingResult:1个错误   字段“ fileData”上对象“员工”的字段错误:拒绝的值[org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@25d17d23];代码[typeMismatch.employee.fileData,typeMismatch.fileData,typeMismatch.org.springframework.web.multipart.commons.CommonsMultipartFile,typeMismatch];参数[org.springframework.context.support.DefaultMessageSourceResolvable:代码[employee.fileData,fileData];参数[];默认消息[fileData]];默认消息[未能将类型'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest $ StandardMultipartFile'的属性值转换为属性'fileData'所需的类型'org.springframework.web.multipart.commons.CommonsMultipartFile';嵌套异常为java.lang.IllegalStateException:无法将类型“ org.springframework.web.multipart.support.StandardMultipartHttpServletRequest $ StandardMultipartFile”的值转换为属性“ fileData”的所需类型“ org.springframework.web.multipart.commons.CommonsMultipartFile” :找不到匹配的编辑器或转换策略]

我正在使用Spring Boot,并且执行了以下操作:

application.properties

# multipart
multipart.enabled=true
spring.http.multipart.max-file-size=500000KB
spring.http.multipart.max-request-size=500000KB

我的GET和POST方法的处理方式如下:

  @GetMapping("/add-employee")
    public ModelAndView empAdmin(Model model) {
        Employee employee=new Employee();
        model.addAttribute("employee", employee);
        return new ModelAndView("add-new-employee");
    }

    // POST: Save product
    @RequestMapping(value = { "/add-employee" }, method = RequestMethod.POST)
    public String productSave(@ModelAttribute("employee") Employee employee)

    {      
        employeeService.saveEmployee(employee);

        return "redirect:/add-employee";
    }

我的服务类别是:

import com.ashwin.vemployee.model.Employee;
import com.ashwin.vemployee.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EmployeeService {

    @Autowired
    private EmployeeRepository empRepository;

    public Employee saveEmployee(Employee employee){
        byte[] image = employee.getFileData().getBytes();
        if (image != null && image.length > 0) {
            employee.setImage(image);
        }
        if(employee.getiNumber()==null){
            empRepository.save(employee);
        }
        else{
            empRepository.save(employee);
        }
        return  employee;
    }

}

我的add-new-employee.jsp如下:

<form:form modelAttribute="employee" method="POST" enctype="multipart/form-data">

    <label>iNumber</label>
    <form:input path="iNumber" id="iNumber" type="text" class="form-control" required="required" />

    <label>Full Name:</label>
    <form:input path="fullName" id="fullName" type="text" class="form-control" required="required" />

    <label>Joined Date</label>
    <form:input path="joinedDate" id="joinedDate" type="text" class="form-control" required="required" />

    <label>Position</label>
    <form:input path="position" id="position" type="text" class="form-control" required="required" />

    <label>Reports To</label>
    <form:input path="reportsTo" id="reportsTo" type="text" class="form-control" required="required" />

    <label>Cubicle No</label>
    <form:input path="cubicleNo" id="cubicleNo" type="text" class="form-control" required="required" />

    <label>Job type</label>
    <form:input path="jobType" id="jobType" type="text" class="form-control" required="required" />

    <td>Upload Image</td>
    <td>
        <form:input type="file" path="fileData" />
    </td>
    <td> </td>

    <input type="submit" value="Submit" />
    <input type="reset" value="Reset" />

</form:form>

为处理上传文件选项,我添加了<form:input type="file" path="fileData" />。 我的模型类如下Employee.java.

    import org.springframework.web.multipart.commons.CommonsMultipartFile;

    import javax.persistence.*;
    import javax.validation.constraints.NotBlank;
    import java.util.Date;

    @Entity
    @Table(name = "employee")
    public class Employee {

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer id;

        @NotBlank
        private String iNumber;

        @NotBlank
        private String fullName;

    //    @NotBlank
        private String joinedDate;

        @NotBlank
        private String position;

        @NotBlank
        private String reportsTo;

        @NotBlank
        private String cubicleNo;

        @NotBlank
        private String jobType;

        @Lob
        @Column(name = "Image", length = Integer.MAX_VALUE, nullable = true)
        private byte[] image;

        // Upload file.
        //@Transient
        private CommonsMultipartFile fileData;

//all default construcotr and getters and setters

我在pom.xml中添加了新的依赖项。

<dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.1</version>
        </dependency>

我的整个pom.xml看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ashwin</groupId>
    <artifactId>vemployee</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>vemployee</name>
    <description>Demo project for Spring Boot for offc</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <!-- https://mvnrepository.com/artifact/jstl/jstl -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- needed for jsp -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <version>9.0.27</version>
        </dependency>

        <!--bootsrap and jquery-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>4.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.4.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.webjars/bootstrap-datepicker -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap-datepicker</artifactId>
            <version>1.7.1</version>
        </dependency>

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

为什么我会收到此错误?

2 个答案:

答案 0 :(得分:2)

如果有图像数据,可以在下面尝试获取请求部分。

 // POST: Save product
        @RequestMapping(value = { "/add-employee" }, method = RequestMethod.POST, consumes = {"multipart/form-data"})
        public String productSave(@ModelAttribute("employee") Employee employee,  @RequestPart("file") MultipartFile file)

        {      
            employeeService.saveEmployee(employee);

            return "redirect:/add-employee";
        }

另一种解决方案是对图像进行64位编码并作为字符串发送,然后在服务层对其进行解码。

答案 1 :(得分:0)

您不应在班级中将多部分文件称为CommonsMultipartFile,而只是MultiPartFile