Spring文件上传指南问题

时间:2015-06-26 15:02:00

标签: java spring jsp spring-mvc

我正在开发一个简单的Spring项目,以便习惯它并跟随他们在网站上的文件上传指南: http://spring.io/guides/gs/uploading-files/

我没有克隆他们的回购,而是将文件添加到现有项目中,我相信这可能是我的问题所在。

这就是我所拥有的:

FileUploadController.java

package webapp;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController {
    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public String uploadForm(Model model) {
        return "upload";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST, headers = "Content-Type=multipart/form-data")
    public @ResponseBody String handleFileUpload(
            @RequestParam(value = "name", required = true) String name,
            @RequestParam("file") MultipartFile file) {
        System.out.println("Got post request");
        String homeLink = "<br /><br /><a href=\"/\">Home<//a>";
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(new File(name)));
                stream.write(bytes);
                stream.close();
                String t = "You successfully uploaded " + name + "!" + homeLink;
                System.out.println(t);
                return t;
            } catch (Exception e) {
                String t = "You failed to upload " + name + " => "
                        + e.getMessage() + homeLink;
                System.out.println(t);
                return t;
            }
        } else {
            String t = "You failed to upload " + name
                    + " because the file was empty." + homeLink;
            System.out.println(t);
            return t;
        }
    }

}

upload.jsp

<!DOCTYPE html>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<html>
<body>
    <p>
        <form:form method="post" enctype="multipart/form-data"
            action="@{/upload}"> File to upload: <form:input
                name="file" type="file" path="file" />
            <br /> Name: <form:input type="text" name="name" path="name" />
            <input type="submit" value="Upload" /> Press here to upload
        the file.
        </form:form>
</body>
</html>

的web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<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_2_5.xsd"
         id="WebApp_ID" version="2.5">

    <display-name>webapp</display-name>

   <!--
        - Location of the XML file that defines the root application context.
        - Applied by ContextLoaderListener.
    -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/application-config.xml</param-value>
    </context-param>

    <!--  <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener> -->


    <!--
        - Servlet that dispatches request to registered handlers (Controller implementations).
    -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

MVC-config.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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="webapp" />


    <mvc:annotation-driven />

    <bean
        class="
        org.springframework.web.servlet.view.InternalResourceViewResolver ">
        <!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

我收到错误

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.RuntimeException: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute

当我更改upload.jsp以使用常规表单时,表单加载正常,但在提交表单时我遇到了问题。

<html>
<body>
    <p>
        File to upload:
        <form method="post" enctype="multipart/form-data" action="upload">
<input name="file" type="file" />
        <br /> Name: <input type="text" name="name" /> <br /> <br />
        <input type="submit" value="Upload" /> Press here to upload the file.
    </form></body>
</html>

提交表单并输入姓名/文件后,我得到:Required String parameter 'name' is not present

很抱歉所有的代码,我是Spring的新手,不知道问题出在哪里。感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

如果您不使用spring mvc标签,那么表单标签应该如下所示

<form method="POST" action="uploadFile" enctype="multipart/form-data">
    File to upload: <input type="file" name="file"><br /> 
    Name: <input type="text" name="name"><br /> <br /> 
    <input type="submit" value="Upload"> Press here to upload the file!
</form>    

在你的spring mvc控制器中,你需要配置如下所示的请求参数

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public @ResponseBody
String uploadFileHandler(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {
//process request
}

对于spring mvc中的文件上传,你必须使用spring mvc的多部分解析器来解析具有file size属性的请求类型。在pom.xml中添加以下依赖项

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

在applicationcontext.xml

中设置bean
<beans:bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

     <!-- setting maximum upload size -->
    <beans:property name="maxUploadSize" value="100000" />

有关文件上传的更多信息,请参阅this