简体   繁体   中英

Uploading file using Spring MVC

UPDATE: I have made the observation that the cause of the null value being passed is enctype="multipart/form-data" , but that part is needed in order to pass the file to the controller. The issue below remains.


I have been trying to set up a Spring MVC page that will allow the user to upload a document. I've looked around and seem to have a general idea on how I should go about implementing this (using "commons-fileupload" and "commons-io") so the following is my view, controller and model.

View:

<%@ 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:

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

Model:

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

I'm new to Spring, and MVC in general, but I'm slowly getting the hang of it. The issue here is that I am in fact entering the Controller's public String create(@Valid UploadForm UploadForm, BindingResult result) method, but UploadForm is being passed as a null value and I can't, for the life of me, figure it out and it's getting quite frustrating. Any help or hints will be greatly appreciated. Thanks!

In your servlet.xml you have to add:

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

This is achievbale using 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>

Model class

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

In the controller

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

Read the file

BufferedReader br = new BufferedReader(
new InputStreamReader(fileuploaded.getFileData().getInputStream()));
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>  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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