Spring MVC文件上传示例

Spring MVC提供了一种简单的方法来上传文件,可以是图像或其他文件。让我们看一个使用Spring MVC上传文件的简单示例。

所需的Jar文件

要运行此示例,您需要加载以下jar文件:

  • Spring Core jar文件
  • Spring Web jar文件
  • commons-fileupload.jar 和 commons-io.jar 文件
  1. 下载包括core、web、aop、mvc、j2ee、remoting、oxm、jdbc、orm等所有Spring的jar文件。
  2. 下载 commons-io.jar
  3. 下载 commons-fileupload.jar

Spring MVC文件上传步骤(比MVC多的步骤)

  1. 添加 commons-io 和 fileupload.jar 文件
  2. 在 spring-servlet.xml 中添加 CommonsMultipartResolver 的条目

    <bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

  3. 创建提交文件的表单。方法名称必须为 "post",enctype 为 "multiple/form-data"。

    <form action="savefile" method="post" enctype="multipart/form-data">
    Select File: <input type="file" name="file"/>
    <input type="submit" value="Upload File"/>
    </form>

  4. 在控制器中使用 CommonsMultipartFile 类。

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

        String path=session.getServletContext().getRealPath("/");  
        String filename=file.getOriginalFilename();  
          
        System.out.println(path+" "+filename);  
        try{  
        byte barr[]=file.getBytes();  
          
        BufferedOutputStream bout=new BufferedOutputStream(  
                 new FileOutputStream(path+"/"+filename));  
        bout.write(barr);  
        bout.flush();  
        bout.close();  
          
        }catch(Exception e){System.out.println(e);}  
        return new ModelAndView("upload-success","filename",path+"/"+filename);  
    }  
    
  5. 在JSP中显示图像。

    <h1>Upload Success</h1>


Spring MVC文件上传示例

创建 images 目录

在您的项目中创建 "images" 目录,因为我们将代码编写为将所有文件保存在 "/images" 目录中。

index.jsp

<a href="uploadform">Upload Image</a>  

Emp.java

package cn.javatiku;  
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

在这里,您需要为 CommonsMultipartResolver 创建一个bean。

<?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="cn.javatiku"></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

在这里,表单必须是 method="post" 和 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 - javatiku</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>  

输出

spring-mvc-file-upload-output1.png

spring-mvc-file-upload-output2.png

spring-mvc-file-upload-output3.png

前往服务器控制台上打印的路径,以查看已上传的文件。


下载 Spring MVC 文件上传示例

我们在 MyEclipse IDE 中创建了此应用程序,该IDE已经提供了jar文件。如果您使用 Eclipse 或其他IDE,您需要加载Spring MVC的jar文件。

标签: spring, Spring教程, Spring技术, Spring语言学习, Spring学习教程, Spring下载, Spring框架, Spring框架入门, Spring框架教程, Spring框架高级教程, Spring面试题, Spring笔试题, Spring编程思想