利用MultipartFile实现文件上传

导入需要使用的jar包

commons-fileupload-xxx.jar    
 commons-io-xxx.jar 等等

在mvc配置文件中:

	    <!-- 文件上传解析器 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- one of the properties available; the maximum file size in bytes -->
        <property name="maxUploadSize" value="5400000"/>
    </bean>


前端使用表单提交

     <form id="Form5" name="Form5" action="<%=basePath%>kh/importFile">
          选择上传文件:<input type="file" name="file1" id="file1">
    		
    		<input type="button" id="imp_btn" οnclick="importFile()" value="导 入">
       
     </form>

在提交之前要先判断提交的文件是否为空,是否为表格,然后ajaxSubmit

	$("#imp_btn").attr("disabled",true);
	var path = $("#file1").val(); 
	if(path==null || path==""){
		alert("请选择上传文件");
		$("#imp_btn").removeAttr("disabled");
		return false;
	}
        var okText = /xls|xlsx/;  //这里是允许的扩展名
        var newFileName = path.split('.'); //这是将文件名以点分开,因为后缀肯定是以点什么结尾的.
        newFileName = newFileName[newFileName.length-1];//这个是得到文件后缀,因为split后是一个数组所以最后的那个数组就是文件的后缀名.newFileName.length为当前的长度,-1则为后缀的位置,因为是从0开始的
       //开始检查后缀
       if (newFileName.search(okText) == -1) {//search如果没有刚返回-1.这个如果newFileName在okText里没有,则为不允许上传的类型. .
          alert("上传文件格式必须为表格");//提示
          //location.reload();
          $("#imp_btn").removeAttr("disabled");
           return false;
       }
       $("#Form5").ajaxSubmit({
  		 type: "Post",
  		 dataType:"jsonp",
  		//data: $('#Form2').serialize(),
  		 //url:"<%=basePath%>kh/importFile",
  		 async:true,
         success:function(result){
        	 result = $.parseJSON(result.replace(/<.*?>/ig,""));
             //console.log(result);
              //新增成功
              if(result.state==1){
            	  alert(result.message);
                  $("#imp_btn").removeAttr("disabled");
                  reloadKhInfo();
                  //window.location.href='<%=basePath %>mobile/week/fotoThirdPage?zbid='+result.data;
             	  //	window.event.returnValue=false;
				  }else{//新增失败
					alert(result.message);
					 $("#imp_btn").removeAttr("disabled");
					//$("#imp_btn").removeAttr("disabled");
					reloadKhInfo();
					return false;
				}             
           },error:function(result){
           alert("插入失败");
     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值