使用Spring MVC上传文件

时间:2013-03-07 02:03:03

标签: java spring-mvc file-upload

更新:我已经观察到传递空值的原因是enctype="multipart/form-data",但是需要该部分才能将文件传递给控制器​​。以下问题仍然存在。


我一直在尝试设置一个允许用户上传文档的Spring MVC页面。我环顾四周,似乎对如何实现这一点有了一个大概(使用“commons-fileupload”和“commons-io”),所以以下是我的视图,控制器和模型。

查看:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ page session="false" %>
<html>
<head>
<title>Upload Document</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">     

    </script>
    <script type="text/javascript" src="resources/rulesextractor.js"></script>
    <link rel="stylesheet" type="text/css" href="./resources/css/rulesextractor.css" />     
</head>
<body>
<c:import url = "./header.jsp">
    <c:param name = "title" value = "Upload Document"/>
    <c:param name = "region" value = "${region}"/>
</c:import>
<br>
    Please choose a Document to upload
<br>

<form:form method="POST" modelAttribute="uploadForm" commandName="uploadForm" name="uploadForm" id="uploadForm" enctype="multipart/form-data">
    <form:input path="fileData" name="fileData" type="file"/>
<br>
    <input type="submit" name="submit" value="Submit" id="subbtn"/>
    <input type="button" value="Main Menu" onclick="back();"/>
</form:form>

</body>
</html>

控制器:

@Controller
public class UploadController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(FlowController.class);

//@Autowired
//private UserPreferences userPreferences;  

@Autowired 
GenericSearchBO genericSearchBO;

@RequestMapping(value = "upload", method = RequestMethod.GET)
public String getUploadPage(Model m){
    logger.info("UploadController: Getting Upload page");
    updateRegionOnModel(m);
    m.addAttribute(new UploadForm());
    return "/pages/upload";
}
@RequestMapping(method = RequestMethod.POST)
public String create(@Valid UploadForm UploadForm, BindingResult result){
    if (result.hasErrors())
    {
      for(ObjectError error : result.getAllErrors())
      {
        System.err.println("Error: " + error.getCode() +  " - " + error.getDefaultMessage());
      }
      return "/pages/upload";
    }

    // Some type of file processing...
    System.err.println("-------------------------------------------");
    //.getOriginalFilename()
    System.err.println("Test upload: " + UploadForm.getFileData());
    System.err.println("-------------------------------------------");

    return "redirect:/pages/upload";
}
}

型号:

public class UploadForm {

private CommonsMultipartFile fileData;

public CommonsMultipartFile getFileData() {
    System.out.println("REACHED GET METHOD");
    return fileData;
}
public void setFileData(CommonsMultipartFile fileData) {
    System.out.println("REACHED SET METHOD");
    this.fileData = fileData;
}
}

我是Spring的新手,一般都是MVC,但我正慢慢掌握它。这里的问题是我实际上正在进入Controller的public String create(@Valid UploadForm UploadForm, BindingResult result)方法,但是UploadForm作为一个空值被传递,我不能,在我的生活中,弄清楚它并且它变得非常令人沮丧。任何帮助或提示将不胜感激。谢谢!

3 个答案:

答案 0 :(得分:1)

在servlet.xml中,您必须添加:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="100000"/>
</bean>

答案 1 :(得分:0)

这是使用multipart / form-data

实现的
<form:form id="" action="xxx.do" method="post"
      modelAttribute="uploadFile"  enctype="multipart/form-data">  
<form:input path="data" id="data" type="file" />
</form:form>

模型类

public class uploadFile{
       private CommonsMultipartFile data; 
       //getter and setter
}

在控制器中

@RequestMapping(value = "/upload", method = RequestMethod.POST)  
public ModelAndView fileUpload(uploadFile fileuploaded,
                               BindingResult result, 
                               HttpSession session){
                       ...
}

阅读文件

BufferedReader br = new BufferedReader(
new InputStreamReader(fileuploaded.getFileData().getInputStream()));

答案 2 :(得分:0)

index.jsp
<a href="uploadform">Upload Image</a>  
Emp.java
package com.javatpoint;  
import java.io.BufferedOutputStream;  
import java.io.File;  
import java.io.FileOutputStream;  
import javax.servlet.ServletContext;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.http.HttpSession;  
import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
import org.apache.commons.fileupload.servlet.ServletFileUpload;  
import org.springframework.stereotype.Controller;  
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 org.springframework.web.servlet.ModelAndView;  

@Controller  
public class HelloController {  
    private static final String UPLOAD_DIRECTORY ="/images";  

    @RequestMapping("uploadform")  
    public ModelAndView uploadForm(){  
        return new ModelAndView("uploadform");    
    }  

    @RequestMapping(value="savefile",method=RequestMethod.POST)  
    public ModelAndView saveimage( @RequestParam CommonsMultipartFile file,  
           HttpSession session) throws Exception{  

    ServletContext context = session.getServletContext();  
    String path = context.getRealPath(UPLOAD_DIRECTORY);  
    String filename = file.getOriginalFilename();  

    System.out.println(path+" "+filename);        

    byte[] bytes = file.getBytes();  
    BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(  
         new File(path + File.separator + filename)));  
    stream.write(bytes);  
    stream.flush();  
    stream.close();  

    return new ModelAndView("uploadform","filesuccess","File successfully saved!");  
    }  
}  
web.xml
<?xml version="1.0" encoding="UTF-8"?>  
<web-app version="2.5"   
    xmlns="http://java.sun.com/xml/ns/javaee"   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
 <servlet>  
    <servlet-name>spring</servlet-name>  
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    <load-on-startup>1</load-on-startup>  
</servlet>  
<servlet-mapping>  
    <servlet-name>spring</servlet-name>  
    <url-pattern>/</url-pattern>  
</servlet-mapping>  
</web-app>  
spring-servlet.xml
Here, you need to create a bean for CommonsMultipartResolver.

<?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.javatpoint"></context:component-scan>  

<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="multipartResolver"   
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>  

</beans>  
uploadform.jsp
Here form must be method="post" and enctype="multipart/form-data".

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>  

<!DOCTYPE html>  
<html>  
 <head>  
 <title>Image File Upload</title>  
 </head>  
 <body>  
<h1>File Upload Example - JavaTpoint</h1>  

<h3 style="color:red">${filesuccess}</h3>  
<form:form method="post" action="savefile" enctype="multipart/form-data">  
<p><label for="image">Choose Image</label></p>  
<p><input name="file" id="fileToUpload" type="file" /></p>  
<p><input type="submit" value="Upload"></p>  
</form:form>  
</body>  
</html>