spring mvc 文件上传

本文介绍如何在SpringMVC中实现文件上传功能,包括设置前端表单属性、配置Spring-servlet.xml文件来限定文件大小及类型,并通过控制器处理文件上传逻辑。

spring mvc 文件上传

在前台页中把form enctype属性设置为"multipart/form-data"
上传多个文件时,保持<input type=file name="files">中的name相同

接下来配置spring-servlet.xml 文件,增加如下内容:
  <!-- SpringMVC上传文件 -->  
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="defaultEncoding" value="UTF-8"/>  
        <!-- 指定所上传文件的总大小不能超过2000KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->  
        <property name="maxUploadSize" value="20000000"/>  
    </bean>
    <!-- 文件上传异常,进入controller之前检查文件 -->
    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
        <property name="exceptionMappings">  
            <props>  
                <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到error页面 -->  
                <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">common/error.jsp</prop>  
            </props>  
        </property>  
    </bean>  
 控制器
@RequestMapping(value="Save",method=RequestMethod.POST)
	public ModelAndView addSavefile(@Valid Pro pro ,
		@RequestParam MultipartFile[] myfiles, HttpServletRequest request,String platformname){
		 try {
		ModelAndView view=new ModelAndView();
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
		String time=df.format(new Date());//获得当前时间
		//设置pro userid
		if(super.getIdenInfo().equals(CConstants.ADMIN)){
			pro.setUserid(super.getUserId());
			pro.setCreateuserid(super.getUserId());
		}else{
			pro.setClientid(super.getClientid());
			pro.setCreateuserid(super.getClientid());
		}
		//获得1-1000之间的随机数
		Random r = new Random();
		int random = Math.abs(r.nextInt())%1000+1; 
		String logpath=request.getSession().getServletContext().getRealPath("/upload/logs/");
		String logname=time+"_"+random+".zip";
		//上传文件名处理,图片文件 文件名路径:WEB-INF/upload/images/时间_随机数
		for(MultipartFile myfile : myfiles){//只允许上传指定格式文件
			boolean iszip=myfile.getOriginalFilename().lastIndexOf(".zip") != -1;
			boolean israr=myfile.getOriginalFilename().lastIndexOf(".rar") != -1;
			  if(!myfile.isEmpty()){  
				if(iszip || israr){
					FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(logpath, logname));
					problem.setLogurl(logname);
				  }else{
					  view.addObject("result", "文件上传失败,文件格式错误");
				  }
			  }
		}//省略部分代码



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值