springMVC文件上传案例

上传单个文件

1、在pom.xml中注入上传文件所需要的依赖

<!-- 文件上传所依赖的jar包 -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>

2、在前端控制器配置文件
2.1、配置包扫描路径"com.springmvc.controller",并且只扫描规定路径下的Controller标签

 <!-- 扫描路径 -->
    <context:component-scan base-package="com.springmvc.controller" >
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

2.2、视图层配置,加入上传文件所需的Bean

<!-- 视图层配置 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp"/>
    </bean> 
<!--200*1024*1024即200M resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常 -->
	 <bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="209715200" />
		<property name="defaultEncoding" value="UTF-8" />
		<property name="resolveLazily" value="true" />
	</bean>

3、新建一个上传单个文件的页面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>上传单个文件示例</title>

<link rel="stylesheet" href="<%=request.getContextPath()%>/resources/css/main.css" type="text/css" />
</head>
<body>
<div align="center">

<h1>上传附件</h1>
<form method="post" action="/HelloSpringMVC/hello/doUpload" enctype="multipart/form-data">
<input type="file" name="file"/>
<button type="submit" >提交</button>
</form>
</div>
</body>
</html>

(1)form表单提交的类型一定要加上enctype=“multipart/form-data”,表示不对所提交的内容编码。
(2)action="" 路径中前面要加项目名,这里项目名是HelloSpringMVC。
(3)doUpload是本表单所提交的对应的处理方法。名为doUpload。
(4)input节点的name="file"中的file与doUpload方法所接收的参数名称一致。

4、定义访问成功的页面

<%@ 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>
<link rel="stylesheet" href="<%=request.getContextPath()%>/resources/css/main.css" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传文件成功 页面</title>
</head>
<body>
<div align="center">
<h1>Success</h1>
</div>
</body>
</html>

5、在Controller类中加入访问入口方法及上传文件相应方法

//定位到上传文件界面 /hello/upload
		@RequestMapping(value="/upload", method=RequestMethod.GET)
		public String showUploadPage(){	
			return "uploadFile";		 //上传单个文件
		}
/**
		 * 上传单个文件操作
		 * @param multi
		 * @return
		 */
		@RequestMapping(value="/doUpload", method=RequestMethod.POST)
		public String doUploadFile(@RequestParam("file") MultipartFile file){

			if(!file.isEmpty()){
				log.debug("Process file: {}", file.getOriginalFilename());
				try {
					//这里将上传得到的文件保存至 /Users/liyanjun/Downloads/ 目录
					FileUtils.copyInputStreamToFile(file.getInputStream(), new File("/Users/liyanjun/Downloads/", 
							System.currentTimeMillis()+ file.getOriginalFilename()));
				} catch (IOException e) {
					e.printStackTrace();
					log.error(e.toString());
				}
			}

			return "success";
		}

6、运行验证


点击提交按钮后在downlods文件夹下查看上传文件

上传多个文件

步骤1、2、4与上传单个文件一致
3、新建一个上传多个文件的页面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>上传多个文件示例</title>

<link rel="stylesheet" href="<%=request.getContextPath()%>/resources/css/main.css" type="text/css" />
</head>
<body>
<div align="center">
<h1>上传多个附件</h1>
<form method="post" action="/HelloSpringMVC/hello/doMultiUpload" enctype="multipart/form-data">
<input type="file" name="file1"/>
<br/>
<input type="file" name="file2"/>
<button type="submit" >提交</button>
</form>

</div>
</body>
</html>

注:
(1)form表单提交的类型一定要加上enctype=“multipart/form-data”,表示不对所提交的内容编码。
(2)action="" 路径中前面要加项目名,这里项目名是HelloSpringMVC。
(3)doMultiUpload是本表单所提交的对应的处理方法。名为doMultiUpload。
(4)要传几个文件就加入几个 不过name的值要不同

5、在Controller类中加入访问入口方法及上传文件相应方法

//定位到上传多个文件界面 /hello/uploadMulti
		@RequestMapping(value="/uploadMulti", method=RequestMethod.GET)
		public String showUploadPage2(){	
			return "uploadMultifile";		 //view文件夹下的上传多个文件的页面
		}
/**
		 * 上传多个附件的操作类
		 * @param multiRequest
		 * @return
		 * @throws IOException
		 */
		@RequestMapping(value="/doMultiUpload", method=RequestMethod.POST)
		public String doUploadFile2(MultipartHttpServletRequest multiRequest) throws IOException{

			Iterator<String> filesNames = multiRequest.getFileNames();
			while(filesNames.hasNext()){
				String fileName =filesNames.next();
				MultipartFile file =  multiRequest.getFile(fileName);
				if(!file.isEmpty()){
					log.debug("Process file: {}", file.getOriginalFilename());
					FileUtils.copyInputStreamToFile(file.getInputStream(), new File(" /Users/liyanjun/Downloads/", 
							System.currentTimeMillis()+ file.getOriginalFilename()));
				}

			}

			return "success";
		}

注:
1、这里与上传单个文件处理方法不同的是接收参数由MultipartFile类型变为了MultipartHttpServletRequest。

2、MultipartFile由MultipartHttpServletRequest对象的getFile(fileName)方法获得。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值