SpringMVC_05_文件上传

分为单文件上传和多文件上传。

直接通过例子介绍:

1.需要在spring-mvc.xml引入beans:

<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="UTF-8"/>  
	    <property name="maxUploadSize" value="10000000"/>
	</bean>

默认编码方式:utf-8

上传最大大小:10000000

 2.引入相关jar包

3.Controller:

	@RequestMapping("/upload")
	public String uploadFile(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws Exception{
		String filePath = request.getServletContext().getRealPath("/");
		System.out.println(filePath);
		file.transferTo(new File(filePath+"upload/"+file.getOriginalFilename()));
		return "redirect:success.html";
	}

把文件下载到根目录下的upload文件夹下,文件名字用之前文件名。

4.界面:

<form action="upload.do" method="post" enctype="multipart/form-data">
<table>
	<tr>
		<th colspan="2">文件上传</th>
	</tr>
	<tr>
		<td>文件一</td>
		<td><input type="file" name="file"></td>
	</tr>
	<tr>
		<th colspan="2"><input type="submit" value="上传"></th>
	</tr>
</table>
</form>

enctype="multipart/form-data"要有,一定使用post

测试:

但是你会发现在Eclipse下的项目的upload却找不到1.txt,看一下文件路径:

C:\Users\sherlock\Documents\gao jishu\Eclipse_Photon\workspace_springmvc\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMvc04\

是在eclipse为你生成的目录下,但你通过请求是可以访问到。

下面说,多文件上传:

	@RequestMapping("/uploads")
	public String uploadFiles(@RequestParam("file") MultipartFile[] files,HttpServletRequest request) throws Exception{
		String filePath = request.getServletContext().getRealPath("/");
		System.out.println(filePath);
		for(MultipartFile file:files) {	
			file.transferTo(new File(filePath+"upload/"+file.getOriginalFilename()));
		}
		return "redirect:success.html";
	}
}

就是把参数改成数组即可。

测试:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值