简体   繁体   English

春季启动时图片上传不成功

[英]Image Upload not successful in spring boot

I have a form where I am submitting data with images.But when I click on submit button then I get the following error:我有一个表单,我在其中提交带有图像的数据。但是当我点击提交按钮时,我收到以下错误:

org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'employee' on field 'fileData': rejected value [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@25d17d23]; org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 个错误字段 'fileData' 上的对象 'employee' 中的字段错误:拒绝值 [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@25d17d23] ; codes [typeMismatch.employee.fileData,typeMismatch.fileData,typeMismatch.org.springframework.web.multipart.commons.CommonsMultipartFile,typeMismatch];代码 [typeMismatch.employee.fileData,typeMismatch.fileData,typeMismatch.org.springframework.web.multipart.commons.CommonsMultipartFile,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [employee.fileData,fileData];参数 [org.springframework.context.support.DefaultMessageSourceResolvable: 代码 [employee.fileData,fileData]; arguments [];参数 []; default message [fileData]];默认消息 [fileData]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'org.springframework.web.multipart.commons.CommonsMultipartFile' for property 'fileData';默认消息[无法将'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile'类型的属性值转换为属性'fileData'的必需类型'org.springframework.web.multipart.commons.CommonsMultipartFile'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'org.springframework.web.multipart.commons.CommonsMultipartFile' for property 'fileData': no matching editors or conversion strategy found]嵌套异常是 java.lang.IllegalStateException:无法将“org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile”类型的值转换为属性“fileData”所需的类型“org.springframework.web.multipart.commons.CommonsMultipartFile” : 找不到匹配的编辑器或转换策略]

I am using spring boot and I did the following:我正在使用弹簧靴,我做了以下事情:

application.properties应用程序属性

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

My GET and POST methods are handled as follows:我的 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";
    }

My service class is:我的服务类是:

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

}

My add-new-employee.jsp looks like this:我的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>

For handling the upload file option I added <form:input type="file" path="fileData" /> .为了处理上传文件选项,我添加了<form:input type="file" path="fileData" /> My model class looks like this Employee.java.我的模型类看起来像这个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

I added new dependecy in my pom.xml.我在 pom.xml 中添加了新的依赖项。

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

My whole pom.xml looks like this:我的整个 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>

Why I am getting this error?为什么我收到这个错误?

Can you try below to get request part if image data is there.如果图像数据存在,您可以尝试在下面获取请求部分。

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

another solution is to base 64 encode your image and send as a string and at service layer decode it.另一种解决方案是对您的图像进行 base 64 编码并作为字符串发送,然后在服务层对其进行解码。

你不应该在你的类CommonsMultipartFile多部分文件称为CommonsMultipartFile ,它只是MultiPartFile

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

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