springMVC实现文件上传功能

文件的上传在web项目中使用广泛,springMVC提供了两种方式:

基于servlet3.0的文件上传
基于commons FileUpload的文件上传(常用)

所有文件在项目中的位置:

applicationContext.xml在src目录下
spring-mvc.xml和web.xml在WEB-INF目录下
index.jsp在WebContent下
文件位置

首先建立一个Dynamic web project项目工程,并完成最基本的基于注解的配置;

下面我们先来看一下两种文件上传的不同之处:

基于servlet3.0的文件上传:

1、在web.xml中的DispatcherServlet增加“multipart-config”配置;
2、在springMVC配置文件中增加:配置
基于commons FileUpload的文件上传(常用)
1、需要导入Commons-fileupload.jar和Commons-io.jar
2、在springmvc配置文件中增加:
配置

upload1是基于servlet3.0上传文件:
upload2是基于Commons fileupload上传文件
upload3基于Commons fileupload 上传多个文件(文件数组)

jsp文件:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>


	<form action="upload1" method="post" enctype="multipart/form-data">
		<input type="text" name="title" /><br>
		<input type="file" name="upfile" /><br>
		<input type="submit" value="submit" />
	</form>
	=============================================
	
	
	<form action="upload2" method="post" enctype="multipart/form-data">
		<input type="text" name="title" /><br>
		<input type="file" name="upfile" /><br>
		<input type="submit" value="submit" />
	</form>
	=============================================
	
	
	<form action="upload3" method="post" enctype="multipart/form-data">
		<input type="text" name="title" /><br>
		<input type="file" name="upfile" /><br>
		<input type="file" name="upfile" /><br>
		<input type="submit" value="submit" />
	</form>
</body>
</html>

controller文件:

package com.upload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadController {
	@RequestMapping("upload1")
	public void upload1(@RequestParam(value="title") String title,
            @RequestParam(value="upfile") MultipartFile file,
            HttpServletRequest request){
		System.out.println(title);
		String rootPath=request.getServletContext().getRealPath("/");
		if(!file.isEmpty()){
			try {
				InputStream is=file.getInputStream();
				FileOutputStream fos=new FileOutputStream(
						rootPath+"/"+"upload/"
						+file.getOriginalFilename());
				byte []cache=new byte[is.available()];
				fos.write(cache);
				is.close();
				fos.flush();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@RequestMapping("upload2")
	public void upload2(@RequestParam(value="title") String title,
            @RequestParam(value="upfile") MultipartFile file,
            HttpServletRequest request){
		System.out.println(title);
		String rootPath=request.getServletContext().getRealPath("/");
		try {
			FileCopyUtils.copy(file.getBytes(), 
					new File(rootPath+"/upload",file.getOriginalFilename()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("upload3")
	public void upload3(@RequestParam(value="title") String title,
            @RequestParam(value="upfile") MultipartFile []file,
            HttpServletRequest request){
		System.out.println(title);
		String rootPath=request.getServletContext().getRealPath("/");
		try {
			for(MultipartFile temp:file)
				FileCopyUtils.copy(temp.getBytes(), 
						new File(rootPath+"/upload",temp.getOriginalFilename()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

下面是三个配置文件,我现在把所有的完整的三个代码都贴了出来,并且把不同文件上传需要加的配置都注释掉了,等到真正要用的时候,直接放开就可以了。
web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		 xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
 		 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" 
 		 id="WebApp_ID" 
		 version="4.0">
  <display-name>springmvc_fileupload</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
<!-- 配置DispatcherServlet -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>
  		classpath*:/applicationContext.xml
  	</param-value>
  </context-param>
  
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <servlet>
  	<servlet-name>springmvc</servlet-name>
  	<servet-class>org.springframework.web.servlet.DispatcherServlet</servet-class>
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>/WEB-INF/spring-mvc.xml</param-value>
  	</init-param>
  	<load-on-startup>1</load-on-startup>
  	
  	<!-- 基于servlet3.0实现文件上传需要加上 -->
	<!--<multipart-config></multipart-config> -->
  	
  	<servlet-mapping>
  		<servlet-name>springmvc</servlet-name>
  		<url-pattern>/</url-pattern>
  	</servlet-mapping>
  </servlet>
</web-app>

spring-mvc.xml:

<?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/mvc
	 http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/beans
		 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context
		 http://www.springframework.org/schema/context/spring-context-4.0.xsd">
	
	<!-- 自动扫描且只扫描@Controller -->
	<context:component-scan base-package="com.upload">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	
	<!-- 基于servlet3.0的文件上传 -->
	<!-- bean id="multipartResolver"
		class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
	</bean> -->
	
	<!-- 基于Commons fileupload的文件上传,需要配置MultipartResolver处理器 -->  
    <!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="defaultEncoding" value="UTF-8"/>  
        指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和  
        <property name="maxUploadSize" value="200000"/>  
    </bean>  --> 
    
    
	<!-- 定义JSP文件的位置:视图解析器 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

applicationContext.xml:

<?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:jdbc="http://www.springframework.org/schema/jdbc" 
	xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" 
	xmlns:task="http://www.springframework.org/schema/task"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">
	<description>Spring公共配置 </description>

	<!-- 配置Spring上下文的注解 -->
	<context:annotation-config />
	<!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
	<context:component-scan base-package="com.upload">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	
	<!-- 属性文件位置 -->
	<context:property-placeholder location="classpath:*.properties" />

</beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值