Spring MVC文件上传

I.Spring MVC文件上传需要再引入名为commons-fileupload和commons-io的jar包,可在Struts2里找到所需jar包。


II.配置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>

III.上传

1.上传页面Fileupload.jsp
<body>
	<form action="Upload.do" method="post" enctype="multipart/form-data">
		file:<input type="file" name="file" />
		<input type="submit" value="上传" />
	</form>
</body>

2.FileuploadController

@RequestMapping("/Upload")
	// 除去上传的文件,若是还有其他数据(比如name)则直接在参数中加入String name即可
	// @RequestMapping("file")是必须的,否则无法初始化
	public String fileUpload(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest req) throws IOException {
		/*
		 * 获取上传时文件名
		 * file.getOriginalFilename()
		 */
		// 获取上传文件的路径
		String path = req.getRealPath("/FileUpload");
		InputStream is = file.getInputStream();
		OutputStream os = new FileOutputStream(new File(path,file.getOriginalFilename()));
		int len = 0;
		byte[] buffer = new byte[400];
		while ((len=is.read(buffer)) != -1)
			os.write(buffer, 0, len);
		os.close();
		is.close();
		return "/Index.jsp";
	}

IV.批量上传Batch.jsp

1.批量上传页面Batch.jsp
<body>
	<form action="Batch.do" method="post" enctype="multipart/form-data">
		file:<input type="file" name="file" /><br/>
		file:<input type="file" name="file" /><br/>
		<input type="submit" value="上传" />
	</form>
</body>
2.BatchController(使用数组就好)
@RequestMapping("/Batch")
	public String fileUpload(@RequestParam("file")CommonsMultipartFile file[], HttpServletRequest req) throws IOException {
		/*
		 * 获取上传时文件名
		 * file.getOriginalFilename()
		 */
		// 获取上传文件的路径
		String path = req.getRealPath("/FileUpload");
		for(int i = 0; i < file.length; i++){
			InputStream is = file[i].getInputStream();
			OutputStream os = new FileOutputStream(new File(path,file[i].getOriginalFilename()));
			int len = 0;
			byte[] buffer = new byte[400];
			while ((len=is.read(buffer)) != -1)
				os.write(buffer, 0, len);
			os.close();
			is.close();
		}
		return "/Index.jsp";
	}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值