SpringMVC之文件上传

cloudspring 2014-08-14

        文件上传是项目开发中一个基本的功能实现。

        在SpringMvc中,要实现文件的上传,先要认识两个接口:MultipartHttpServletRequest和MultipartFile。

        MultipartHttpServletRequest接口方法
        interface MultipartHttpServletRequest extends HttpServletRequest {
            public MultipartFile getFile(String name);
            public Map getFileMap();
            public Iterator getFileNames();//获取表单字段的名称,而不是原来的文件名,并存储在迭代器中
        }

        MultipartFile接口方法:
        interface MultipartFile {
            public byte[] getBytes();//将文件的内容作为一个字节数组返回。
            public String getContentType();//获取文件类型
            public java.io.InputStream getInputStream();//获取文件流
            public String getName();//返回页面multipart form中文件name属性的对应名
            public String getOriginalFilename();//返回上传的文件名
            public long getSize();//获取文件长度
            public boolean isEmpty();//判断上传文件是否为空
            public void transferTo(java.io.File dest);//将上传文件输出到指定路径dest下
        }

下面给出一个SpringMVC实现文件上传的实例:

项目结构:
SpringMVC之文件上传        注意:SpringMvc实现上传时需要添加除自身以外的其他依赖包:
SpringMVC之文件上传

<?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">
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<!--filter配置,解决编码问题 -->
	<filter>
		<filter-name>characterEncodingfilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>characterEncodingfilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<servlet>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath*:/config/spring-annotation-servlet.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>
</web-app>
<?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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="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
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
	<!-- 开启注解 -->
	<mvc:annotation-driven />
	<!-- 注解扫描包 -->
	<context:component-scan base-package="cn.upload" />
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!--支持JSTL -->
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
		<property name="prefix" value="/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	<!-- Spring MVC 文件上传配置 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="utf-8"></property>
		<!-- 最大上传文件的大小(单位:字节) -->
		<property name="maxUploadSize" value="10485760000"></property>
		<property name="maxInMemorySize" value="40960"></property>
	</bean>
</beans>
package cn.upload;
import java.io.File;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
@Controller
public class UploadAction {
    @RequestMapping("/upload")
    public void upload(HttpServletRequest request, HttpServletResponse response)
       throws Exception {
       CommonsMultipartResolver multipartResoler = 
            new CommonsMultipartResolver(request.getSession().getServletContext());
       if (multipartResoler.isMultipart(request)) {
          MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
	  Iterator<String> iter = multiRequest.getFileNames();
	  while (iter.hasNext()) {
              MultipartFile file = multiRequest.getFile(iter.next());
		if (file != null) {
			System.out.println("name: "+ file.getName());
			System.out.println("file.name: "+ file.getOriginalFilename());
			String fileName = "demo_uploade_"+ file.getOriginalFilename();
			file.transferTo(new File("d:/" + fileName));
		}
	    }
	}
    }
}
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<base href="<%=basePath%>">
		<title>spring mvc文件上传2</title>
	</head>
	<body>
		<form id="uploadForm" action="<%=basePath%>upload" method="post"
			enctype="multipart/form-data" />
			选择文件1:<input type="file" name="file1" /><br />
			选择文件2:<input type="file" name="file2" /><br />
			选择文件3:<input type="file" name="file3" /><br />
			<input type="submit" value="上传" />
		</form>
	</body>
</html>

         运行:
SpringMVC之文件上传

相关推荐