簡體   English   中英

春季啟動時圖片上傳不成功

[英]Image Upload not successful in spring boot

我有一個表單,我在其中提交帶有圖像的數據。但是當我點擊提交按鈕時,我收到以下錯誤:

org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 個錯誤字段 'fileData' 上的對象 'employee' 中的字段錯誤:拒絕值 [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” : 找不到匹配的編輯器或轉換策略]

我正在使用彈簧靴,我做了以下事情:

應用程序屬性

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

為什么我收到這個錯誤?

如果圖像數據存在,您可以嘗試在下面獲取請求部分。

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

另一種解決方案是對您的圖像進行 base 64 編碼並作為字符串發送,然后在服務層對其進行解碼。

你不應該在你的類CommonsMultipartFile多部分文件稱為CommonsMultipartFile ,它只是MultiPartFile

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM