spring上传文件-two

本文详细介绍了使用Spring MVC实现文件上传的功能,包括配置文件解析器、处理multipart请求、上传文件到本地以及处理上传文件大小限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Controller里面
public String upload(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
//解析器解析request的上下文
CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext()); 
//先判断request中是否包涵multipart类型的数据,
if(multipartResolver.isMultipart(request)){
  //再将request中的数据转化成multipart类型的数据
 MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
 Iterator iter = multiRequest.getFileNames();
 while(iter.hasNext()){
 MultipartFile file = multiRequest.getFile((String)iter.next());
 if(file != null){
 String fileName = file.getOriginalFilename();
 String path = "H:/" + fileName;
 File localFile = new File(path);
 //写文件到本地
 file.transferTo(localFile);
   }
  }
 }


return "login";
}
applicationContext.xml里面
<bean id="downAndUploadController" class="com.luck.web.controller.DownAndUploadController">
<property name="methodNameResolver" ref="methodNameResolver"/>
</bean>
<!--springMVC的上传文件-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxInMemorySize" value="40960" />
<property name="maxUploadSize" value="10485760000" />
</bean>
<!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->  
    <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->  
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">downUpload</prop>
</props>
</property>
</bean>


jsp里面
<form action="downUp.do?method=upload" method="post" enctype="multipart/form-data"><!--multipart/form-data表示上传表单 -->
<input type="file" name="file1"/>
<input type="file" name="file2"/>
<input type="file" name="file3"/>//多文件上传时 name不能相同
<input type="file" name="file4"/>
<input type="submit" value="上传文件"/>
</form>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值