SpringMVC 实现文件上传

SpringMVC实现文件上传很简单,spring本身的使用也非常简单,要使用spring的某些功能,只需要在spring

的配置文件声明对应的功能的bean即可,如题,我们这里要用到的文件上传的bean是MultipartResolver。

第一步:加入到配置文件

<!-- 上传文件bean -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
		<property name="defaultEncoding" value="utf-8" /> <property name="maxUploadSize" 
		value="5400000000" /> <property name="maxInMemorySize" value="40960" /> 
	</bean>

其中maxUploadSize="5400000000" 是上传文件的大小,单位为字节


第二步:配置Controller中的请求

@RequestMapping({"/resourceFileUpload"})
   public String fileUpload(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
	   if(!file.isEmpty()) {
		   try {
			   String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"  + file.getOriginalFilename();
			   System.out.println(filePath);
			   file.transferTo(new File(filePath));
			   //file.transferTo(new File("E:/" + file.getOriginalFilename()));
		   }catch(Exception e) {
			   e.printStackTrace();
		   }
	   }
	   return "";
   }


第三不步:配置请求表单

<form action="/Spring3_SpringMVC_Hibernate4_test2/resource/resourceFileUpload" method="post" enctype="multipart/form-data">
		<h3>文件上传</h3>
		
		选择文件:<input type="file" name="file" id="file" value="" /><input type="submit" value="提交" />
	</form>

其中表单中记得声明 enctype="multipart/form-data"

到这里使用springMVC实现单一文件上传就完成了。



如果要实现多文件上传,也很简单,说一下思路,在jsp中写表单时,添加多个input即可

,上面的例子只有一个

选择文件:<input type="file" name="file" id="file" value="" />

多文件上传,只需要粘贴多个,name相同即可


在controller中,对应请求的action方法的参数配置成数组即可,例如:

public String fileUpload(@RequestParam("file") MultipartFile[] file,HttpServletRequest request) {
......
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值