SpringMvc 文件上传 与 批量上传

1.单文件上传

 1>页面编写

<form action="upload" method="post" enctype="multipart/form-data">
	<span>用户名</span> <input type="text" name="name"/><br/>
	<span>头    像</span> <input type="file" name="file" accept="image/*"/><br/>
	<input type="submit" value="注册">
</form>
2>控制层编写

@PostMapping("/upload")
	public String upload(MultipartFile file,String name,HttpSession session) throws Exception{
		
		System.out.println(name);
		
		String basePath = session.getServletContext().getRealPath("/");
		
		//获取文件名
		String fileName = file.getOriginalFilename();
		System.out.println(fileName);
		
		//目标文件
		File targetFile = new File(basePath,fileName);
		
		//转存文件
		file.transferTo(targetFile);
		
		System.out.println(targetFile.getAbsolutePath());
		
		return "success";
	}
2. 多文件上传

1>页面编写

<form action="upload2" method="post" enctype="multipart/form-data">
	<span>用户名</span> <input type="text" name="name"/><br/>
	<span>文    件1</span> <input type="file" name="files"/><br/>
	<span>文    件2</span> <input type="file" name="files"/><br/>
	<span>文    件3</span> <input type="file" name="files"/><br/>
	<input type="submit" value="提交">
</form>
2>控制层编写
@PostMapping("/upload2")
	public String upload2(MultipartFile[] files,String name,HttpSession session) throws Exception{
		
		System.out.println(name);
		
		String basePath = session.getServletContext().getRealPath("/");
		
		for (int i = 0; i < files.length; i++) {
			MultipartFile file = files[i];
			
			//获取文件名
			String fileName = file.getOriginalFilename();
			System.out.println(fileName);
			
			//目标文件
			File targetFile = new File(basePath,fileName);
			
			//转存文件
			file.transferTo(targetFile);
			
			System.out.println(targetFile.getAbsolutePath());
		}
		
		return "success";
	}

3.SpringMvc配置multipartResolver。

<bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!-- 默认编码 -->
        <property name="defaultEncoding" value="utf-8" />  
        <!-- 文件大小最大值 -->
        <property name="maxUploadSize" value="1000000" />  
        <!-- 内存中的最大值 -->
        <property name="maxInMemorySize" value="40960" />  
    </bean>
4.注意点

form 表单中enctype="multipart/form-data" 不要忘记写。作用:这个form表单可以上传文件。


  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值