2013-10-02 36 views
1

我正在构建一个相当大的表单。用户可以一次性上传图像。仅提交输入文件jQuery表单插件

该图像应立即上传。然后用户应该继续填写表格。

HTML

<form name="registration" id="registration" action="confirm.php" method="post"> 
    <input name="firstname" id="firstname" type="text" /> 
    <input name="lastname" id="lastname" type="text" /> 
    <!-- file upload --> 
    <input name="file" id="file" type="file" /> 
    <input name="newsletter" type="checkbox" id="newsletter" /> 
    <input name="captcha" id="captcha" type="tel" /> 
</form> 

的Javascript(jQuery的)

//upload file on change event 
$('#file').change(function() { 

    // put the image object into a variable 
    // formData is incomaptible with IE9/8/7 
    fileData = new FormData(); 
    fileData.append('file', this.files[0]); 

     var options = { 
      // XMLHttpRequest Level 2 - no cross-browser support 
      data: fileData, 
      url: 'upload.php', // override standard url for this call only 
      type: 'post' 
     }; 

     // make an ajax call to post the image   
     $.ajax(options); 

     // Alternatively use the jQuery Form plugin   
     // $('#registration').ajaxSubmit(options); 


}); 

不幸的是,jQuery的表单插件http://malsup.com/jquery/form/#file-upload提交整个表单,当我想只提交的输入文件中的字段。

此外,我宁愿避免在我的HTML标记中创建多个单独的表单,因为我还需要处理并提交多个表单。

我在这里错过了什么?

+0

<! - 文件上传'-'>应该是<! - 文件上传'--'> – Salim

+0

评论标记已被修复。 –

+0

您在窗体标记中缺少enctype ='multipart/form-data'属性 –

回答

2

您可以使用“beforeSubmit”回调来修改正在提交的表单数据。 为了达到这个目的,我们首先删除不是文件类型的表单数据数组元素,然后使用定义的“干净”原型从数组中删除这些元素。

功能提交文件:

 $('#file').change(function() { 
      $('#registration').ajaxSubmit({ 
       url:'upload.php', 
       type: 'post', 
       beforeSubmit: function (formData, $form, options) { 
        $.each(formData, function (i, obj) { 
         if (obj != null) { 
          if (obj.type != "file") 
           delete formData[i]; //delete the elements which are not required. 
         } 
        }); 
        formData.clean(undefined);//remove deleted elements 
       } 
      }); 
     }); 

干净原型:

Array.prototype.clean = function (deleteValue) { 
     for (var i = 0; i < this.length; i++) { 
      if (this[i] == deleteValue) { 
       this.splice(i, 1); 
       i--; 
      } 
     } 
     return this; 
    }; 

希望这有助于:)

+1

这适用于我。非常感谢! 性能方面,使用$ .each有意义吗?难道我们不想将obj.type“file”推入数组,而不是从数组中删除不需要的formData? 我正在考虑在这里开始移动。 –

+0

是的,如果对象是已知的,你可以推送obj类型文件,我把它写成通用代码,你不知道被引用的表单中的对象的数量和名称。我用于循环,因为拼接需要索引作为一个参数:) –

0

所有你需要做的是设置窗体的隐藏价值,捕获服务器端的值并仅处理文件上传工作,忽略传递给服务器的其他表单变量。这使得它更容易。一旦文件上传工作完成,您可以将隐藏的值设置回来(这次告诉服务器端它应该处理表单的所有变量)。

相关问题