SpringMVC File Upload 多文件上传


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">
	<display-name></display-name>
<!-- 	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
   classpath*:/applicationContext*,classpath*:spring-MVC.xml
  </param-value>
	</context-param> -->
	<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/classes/spring-MVC.xml</param-value>
  </context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	  <servlet>
     <servlet-name>springMvc</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/classes/spring-MVC.xml</param-value>
     </init-param>
     <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
     <servlet-name>springMvc</servlet-name>
     <url-pattern>/</url-pattern>
  </servlet-mapping>
  
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>



spring-MVC.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
             xmlns:mvc="http://www.springframework.org/schema/mvc" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             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.1.xsd 
                http://www.springframework.org/schema/context 
                http://www.springframework.org/schema/context/spring-context-3.1.xsd 
                http://www.springframework.org/schema/mvc 
                http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"> 

	<context:component-scan base-package="com.geloin"/> 
    <mvc:annotation-driven/> 
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
        <property name="prefix" value="/WEB-INF/jsp/"/> 
        <property name="suffix" value=".jsp"/> 
    </bean> 
    
    <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> 
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
        <!-- 指定所上传文件的总大小不能超过2000KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 --> 
        <property name="maxUploadSize" value="2000000"/> 
    </bean> 
     
    <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException --> 
    <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 --> 
    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> 
        <property name="exceptionMappings"> 
            <props> 
                <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 --> 
                <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop> 
            </props> 
        </property> 
    </bean> 
    
	
	<!--对静态资源文件的访问-->
	<mvc:resources mapping="/js/**" location="/WEB-INF/js/" />
    <mvc:resources mapping="/css/**" location="/WEB-INF/css/" />
</beans>



FileUploadController.java

package com.geloin.spring.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.geloin.spring.model.User;
 
/**
 * SpringMVC中的文件上传
 * @see 第一步:由于SpringMVC使用的是commons-fileupload实现,故将其组件引入项目中
 * @see       这里用到的是commons-fileupload-1.2.2.jar和commons-io-2.0.1.jar
 * @see 第二步:在####-servlet.xml中配置MultipartResolver处理器。可在此加入对上传文件的属性限制
 * @see 第三步:在Controller的方法中添加MultipartFile参数。该参数用于接收表单中file组件的内容
 * @see 第四步:编写前台表单。注意enctype="multipart/form-data"以及<input type="file" name="****"/>
 * @author 宏宇
 * @create May 12, 2012 1:26:21 AM
 */ 
@Controller 
@RequestMapping("/user") 
public class FileUploadController { 
    private final static Map<String,User> users = new HashMap<String,User>(); 
     
    //模拟数据源,构造初始数据 
    public FileUploadController(){ 
        users.put("张起灵", new User("张起灵", "闷油瓶", "02200059", "menyouping@yeah.net")); 
        users.put("李寻欢", new User("李寻欢", "李探花", "08866659", "lixunhuan@gulong.cn")); 
        users.put("拓拔野", new User("拓拔野", "搜神记", "05577759", "tuobaye@manhuang.cc")); 
        users.put("孙悟空", new User("孙悟空", "美猴王", "03311159", "sunhouzi@xiyouji.zh")); 
    } 
     
    @RequestMapping("/list") 
    public String list(Model model){ 
        model.addAttribute("users", users); 
        return "user/list"; 
    } 
     
    @RequestMapping(value="/add", method=RequestMethod.GET) 
    public String addUser(){ 
        return "user/add"; 
    } 
    
    @RequestMapping(value="/add", method=RequestMethod.POST) 
    public String addUser(User user, MultipartHttpServletRequest request, HttpServletResponse response) throws IOException{ 
        //如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解 
        //如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且还要指定@RequestParam注解 
        //并且上传多个文件时,前台表单中的所有<input type="file"/>的name都应该是myfiles,否则参数里的myfiles无法获取到所有上传的文件 
    	Iterator<String> itr =  request.getFileNames();
    	MultipartFile myfile = null;
    	 
        //2. get each file
        while(itr.hasNext()){

            //2.1 get next MultipartFile
        	myfile = request.getFile(itr.next()); 
            if(myfile.isEmpty()){ 
                System.out.println("文件未上传"); 
            }else{ 
                System.out.println("文件长度: " + myfile.getSize()); 
                System.out.println("文件类型: " + myfile.getContentType()); 
                System.out.println("文件名称: " + myfile.getName()); 
                System.out.println("文件原名: " + myfile.getOriginalFilename()); 
                System.out.println("========================================"); 
                //如果用的是Tomcat服务器,则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中 
                String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload"); 
                //这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的 
                FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename())); 
            }
        } 
        users.put(user.getUsername(), user); 
        return "redirect:/user/list"; 
    } 
    
} 

User.java

package com.geloin.spring.model;
public class User { 
    private String username; 
    private String nickname; 
    private String password; 
    private String email; 
    /*==四个属性的getter()、setter()略==*/ 
    public User() {} 
    public User(String username, String nickname, String password, String email) { 
        this.username = username; 
        this.nickname = nickname; 
        this.password = password; 
        this.email = email; 
    }
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getNickname() {
		return nickname;
	}
	public void setNickname(String nickname) {
		this.nickname = nickname;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	} 
    
    
} 



upload.jsp

<%@ page language="java" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
<form action="/SpringAndJqueryUpload/user/add" method="POST" enctype="multipart/form-data"> 
<!--     yourfile: <input type="file" name="myfiles"/><br/>  -->
<!--     yourfile: <input type="file" name="myfiles"/><br/>  -->
<!--     yourfile: <input type="file" name="myfiles"/><br/>  -->
    <input type="file" name="files[]" multiple>
    <input type="submit" value="添加新用户"/> 
</form> 
  </body>
</html>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值