CommonsMultipartFile - typeMismatch - PullRequest
       34

CommonsMultipartFile - typeMismatch

0 голосов
/ 12 марта 2020

Я обнаружил эту ошибку при запуске:

ПРЕДУПРЕЖДЕНИЕ: решено [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 ошибка Ошибка поля в объекте 'fileUpload' в данных поля ' ': отклоненное значение [org.springframework.web.multipart.commons. CommonsMultipartFile@c2af65e]; коды [typeMismatch.fileUpload.data, typeMismatch.data, typeMismatch. [B, typeMismatch]; аргументы [org.springframework.context.support.DefaultMessageSourceResolvable: codes [fileUpload.data, data]; аргументы []; сообщение по умолчанию [данные]]; сообщение по умолчанию [Не удалось преобразовать значение свойства типа 'org.springframework.web.multipart.commons.CommonsMultipartFile' в требуемый тип 'byte []' для свойства 'data'; вложенное исключение: java .lang.IllegalArgumentException: невозможно преобразовать значение типа 'org.springframework.web.multipart.commons.CommonsMultipartFile' в требуемый тип 'byte' для свойства 'data [0]': PropertyEditor [org.springframework. beans.propertyeditors.CustomNumberEditor] возвратил недопустимое значение типа 'org.springframework.web.multipart.commons.CommonsMultipartFile']]

Я использую TomCat 9, Java 1.8 Версия, Elipse, Spring MVC , Dynami c Веб-модуль 4.0, MySQL.

PaintPost. java (Контроллер)

package com.ai.jwd21.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.ai.jwd21.model.FileUpload;
import com.ai.jwd21.service.PaintPostService;

@Controller
public class PaintPost {

    @Autowired
    private PaintPostService paintPostService;

    // for inserting the art into the database
    @RequestMapping(value = "/insertPaint", method = RequestMethod.POST)
    public String handleFileUpload(Model model, @ModelAttribute FileUpload fileUpload, @RequestParam CommonsMultipartFile commonsMulti) throws Exception {

        if (commonsMulti != null) {
                System.out.println("Saving file: " + commonsMulti.getOriginalFilename());
                int idNumber = fileUpload.getId();
                String fileName = fileUpload.getFileName();
                byte[] bytes = fileUpload.getData();
                fileUpload.setId(idNumber);
                fileUpload.setFileName(fileName);
                fileUpload.setData(bytes);
                model.addAttribute("insertFile", paintPostService.insertPaint(fileUpload));
        }
        return "uploadPost";
    }
}

PaintPostDao (пакет Дао)

package com.ai.jwd21.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.ai.jwd21.model.FileUpload;

public class PaintPostDao extends BaseDao {

    public Boolean insertPaint(FileUpload uploadFile) {

        // select query

        final String INSERTPAINT = "INSERT INTO artfile values (?,?,?);";

        // get DB Connection
        Connection connection = getConnection();

        try {
            // prepare statement
            PreparedStatement psinsertpaint = connection.prepareStatement(INSERTPAINT);

            psinsertpaint.setInt(1, uploadFile.getId());
            psinsertpaint.setString(2, uploadFile.getFileName());
            psinsertpaint.setBytes(3, uploadFile.getData());
            int rs = psinsertpaint.executeUpdate();

            if (rs > 0) {
                System.out.println("file is in the databse");
                return true;
            }

        } catch (SQLException e) {

            e.printStackTrace();
        }
        return false;

    }

}

FileUpload. java (пакет модели, класс PoJO)

package com.ai.jwd21.model;

public class FileUpload {

    private int id;
    private String fileName;
    private byte[] data;

    public FileUpload() {

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public byte[] getData() {
        return data;
    }

    public void setData(byte[] data) {
        this.data = data;
    }

}

PaintPostService (пакет услуг)

package com.ai.jwd21.service;

import org.springframework.beans.factory.annotation.Autowired;

import com.ai.jwd21.dao.PaintPostDao;
import com.ai.jwd21.model.FileUpload;

public class PaintPostService {

    @Autowired
    private PaintPostDao paintPostDao;

    public FileUpload insertPaint(FileUpload uploadFile) {
        return paintPostDao.insertPaint(uploadFile) ? uploadFile : null;
    }

}

пом. xml

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ai.jwd21</groupId>
    <artifactId>ArtworkHub</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>ArtworkHub</name>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.1.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>3.0-alpha-1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.1.RELEASE</version>
        </dependency>

        <!-- Apache Commons FileUpload -->  
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!-- Apache Commons IO -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version> <!-- or whatever current version -->
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

index. jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>

<style>
body {
    background-image: url("C:/Users/John/Desktop/image/gogh103.jpg");
    background-color: #cccccc;
    background-repeat: no-repeat;
    background-size: cover;
}

table {
    border-collapse: collapse;
    border-spacing: 0;
    color: #4a4a4d;
}

td {
    border: 1px solid #cecfd5;
    padding: 10px 15px;
}

td>label {
    vertical-align: text-top;
    color: black;
}
</style>
</head>
<body>

    <form action="insertPaint" method="post" target="_blank"
        enctype="multipart/form-data">
        <table>

            <caption>Upload your painting</caption>


            <tr>
                <td><label for="id"><b>Id</b></label></td>
                <td><input type="text" name="id" required></td>
            </tr>

            <tr>
                <td><label for="fileName"><b>Painting Name</b></label></td>
                <td><input type="text" placeholder="Enter Username" name="fileName" required></td>
            </tr>

            <tr>
                <td><label for="data">Select image:</label></td>
                <td><input type="file" id="data" name="data"></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Post"></td>
            </tr>

        </table>
    </form>


</body>
</html>

web. xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
  <display-name>ArtworkHub</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

пружинный сервлет. xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
http://www.springframework.org/schema/context  
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.ai.jwd21.controller"></context:component-scan>
    <context:annotation-config />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <bean id="paintService"
        class="com.ai.jwd21.service.PaintPostService"></bean>
    <bean id="paintDao" class="com.ai.jwd21.dao.PaintPostDao"></bean>
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
</beans>

Консоль

Mar 12, 2020 9:21:09 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version name:   Apache Tomcat/9.0.30
Mar 12, 2020 9:21:09 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          Dec 7 2019 16:42:04 UTC
Mar 12, 2020 9:21:09 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version number: 9.0.30.0
Mar 12, 2020 9:21:09 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Windows 10
Mar 12, 2020 9:21:09 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            10.0
Mar 12, 2020 9:21:09 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          amd64
Mar 12, 2020 9:21:09 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             C:\Program Files\Java\jdk1.8.0_181\jre
Mar 12, 2020 9:21:09 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.8.0_181-b13
Mar 12, 2020 9:21:09 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Mar 12, 2020 9:21:09 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         C:\Users\John\eclipse-workspace2\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Mar 12, 2020 9:21:09 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         E:\Desktop\Tomcat\apache-tomcat-9.0.30
Mar 12, 2020 9:21:09 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\Users\John\eclipse-workspace2\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Mar 12, 2020 9:21:09 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=E:\Desktop\Tomcat\apache-tomcat-9.0.30
Mar 12, 2020 9:21:09 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\Users\John\eclipse-workspace2\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
Mar 12, 2020 9:21:09 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=E:\Desktop\Tomcat\apache-tomcat-9.0.30\endorsed
Mar 12, 2020 9:21:09 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Mar 12, 2020 9:21:09 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_181\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\MySQL\MySQL Shell 8.0\bin\;C:\Program Files\Java\jdk1.8.0_181\bin;;.]
Mar 12, 2020 9:21:09 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Mar 12, 2020 9:21:10 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Mar 12, 2020 9:21:10 PM org.apache.catalina.startup.Catalina load
INFO: Server initialization in [1,216] milliseconds
Mar 12, 2020 9:21:10 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Catalina]
Mar 12, 2020 9:21:10 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet engine: [Apache Tomcat/9.0.30]
Mar 12, 2020 9:21:13 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Mar 12, 2020 9:21:13 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Mar 12, 2020 9:21:13 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Mar 12, 2020 9:21:13 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Mar 12, 2020 9:21:13 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in [3,541] milliseconds
Mar 12, 2020 9:21:52 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring DispatcherServlet 'spring'
Mar 12, 2020 9:21:52 PM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: Initializing Servlet 'spring'
Mar 12, 2020 9:21:53 PM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: Completed initialization in 1161 ms
Mar 12, 2020 9:21:54 PM org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver resolveException
WARNING: Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'fileUpload' on field 'data': rejected value [org.springframework.web.multipart.commons.CommonsMultipartFile@c2af65e]; codes [typeMismatch.fileUpload.data,typeMismatch.data,typeMismatch.[B,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [fileUpload.data,data]; arguments []; default message [data]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.commons.CommonsMultipartFile' to required type 'byte[]' for property 'data'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type 'org.springframework.web.multipart.commons.CommonsMultipartFile' to required type 'byte' for property 'data[0]': PropertyEditor [org.springframework.beans.propertyeditors.CustomNumberEditor] returned inappropriate value of type 'org.springframework.web.multipart.commons.CommonsMultipartFile']]
Mar 12, 2020 9:37:43 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/ArtworkHub] has started
Mar 12, 2020 9:37:43 PM org.apache.catalina.core.ApplicationContext log
INFO: Destroying Spring FrameworkServlet 'spring'
Mar 12, 2020 9:37:44 PM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Mar 12, 2020 9:37:45 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Mar 12, 2020 9:37:45 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/ArtworkHub] is completed
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...