使用ajax提交包含文件的表单

实现ajax提交表单的操作,在普通的文件提交方式中,不能通过ajax上传,如果需要文件提交后产生回调函数,则显得苍白无力,

其实可以通过jqery-form.js插件实现

1.前段代码

// 前端代码,(表单提交的内容很多,因为主要是阐述文件提交功能,所以把其他控件删除了)

<form action="#" name="fileForm" id="fileForm" enctype="multipart/form-data" method="post" >
                文件选择:<input type="file" id="addAppFile" name="addAppFile" width="300px">
      <button type="button" id="btn" style="height:23px; width:62px;margin-right:20px; margin-left:50px;" 
οnclick="onSure()"/>确定

      </form>

2.js代码

//"确定“按钮事件

functiononSure(){

//得到表单中的文件内容,存放在一个数组中
var isFile = document.getElementById("addFile").files;
if(isFile.length == 0){
mini.alert("请选择要上传的文件!");
return;
}
       //得到文件上次修改的时间  
var lastDate = isFile[0].lastModifiedDate;
var lastModifiedDate = lastDate.getFullYear() + '-'
+(lastDate.getMonth() + 1) +'-'
+ lastDate.getDate() + ' '
+ lastDate.getHours() + ':'
+ lastDate.getMinutes() + ':'
+ lastDate.getSeconds();

//提交的路径和参数,和成功时候的回调函数

var options={
           url:"url?lastModifiedDate="+lastModifiedDate,
           type:"post",
            success:function(result){
              
            }

 };

 ///给表单注册提交事件
$("#fileForm").submit(function() {
$(this).ajaxSubmit(options);
return false;
 });

//此处设置为点击按钮100毫秒后,提交内容
setTimeout(function(){
$("#fileForm").submit();
        }, 100);
}

//后台java代码

@RequestMapping("/addFile")
@ResponseBody
public String addAppFile(HttpServletRequest request,@RequestParam("addAppFile") MultipartFile uploadFile) throws IOException {

if(!uploadFile.isEmpty()){

//对文件进行操作

}

}

//配置文件,这里省略了其他的配置,只写出和文件上传有关的配置内容

<!-- 配置 MultipartResolver -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="1024000"></property>
</bean>


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值