2017-05-31 77 views
0

我有一个对话框,用户可以选择上传文件。我想上传文件到服务器上单击jQuery对话框中的按钮。我尝试了很多代码,但不幸的是,我找不到解决方案。请帮助我。通过ajax jquery上传多个文件不带表格

我的小提琴 fiddle

的Jquery:

$(function(){ 
$(document).on('click','.click_link',function(){ 
$("#dialog_loader").dialog("open"); 
$("#dialog_loader").css({'display':'show'}); 
return false; 
}); 

$("#dialog_loader").dialog({resizable: false, 
    height:"auto", 
    modal: true, 
    minWidth: 400, 
    autoOpen:false, 
    position: 'center top', 
    buttons: { 
    "Update": function() { 
      var form_data = new FormData(); 
      $.each($("input[type='file']")[0].files, function(i, file) { 
      form_data.append('file', file); 
     }); 
     form_data.append("status", 'update'); 
     $.ajax({ 
      url:path, 
      type:'POST', 
      dataType: "HTML", 
      contentType : false, 
      processData : false, 
      data:form_data, 
      success:function(msg){ 
       if(msg==1) 
       { 
        alert(123); 
       } 
      } 
     }); 
    }, 
    "Approve":function(){ 

    }, 
    Cancel: function() { 
     $(this).dialog("close"); 
    } 
    } 
}); 


$(document).on('click','.add_more',function(e){ 
    e.preventDefault(); 
    var filePresent = document.getElementsByClassName('file')[document.getElementsByClassName('file').length-1].files.length; 
if(filePresent >0 ){ 
    $(this).parent().find('#extra_file_div').find('.file_div_child').append("<br/><input name='file_uploads[]' type='file' class='multi_files file' /><button class='remove'>X</button>"); 
    //$(this).before("<div class='file_div_child'><input name='file_uploads[]' type='file' class='multi_files file' /><button class='remove'>X</button></div>"); 
    } 

}); 

$(document).on('change','input:file', 
     function(){ 
      $('input:file').removeClass('multi_files'); 
     if ($(this).val()) { 
      if($(this).parent().parent().find('.remove').length <1) 
      { 
       $(this).after("<button class='remove first_remove' >X</button>"); 
      } 
      $('.add_more').show(); 
     } 
     else 
     { 
      $('.add_more').hide(); 

     } 
    }); 

$(document).on('click','.remove',function(){ 
var length = $('#dialog_attachments').find(".file").length; 
if(length > 1){ 
    $(this).prev('input:file').remove(); 
    $(this).prev('br').remove(); 
    $(this).remove(); 

} 
else 
{ 
    $(".file").val(''); 
    $(this).remove(); 
    $(this).parent('.file_div_child').find('br').remove(); 
    $('.add_more').hide(); 
} 

return false; 
}); 
}); 

回答

0

我创建了一个表格,并把文件输入部分是表单元素里面。 然后使用jQuery的每个功能,我已经将每个文件输入添加到form_data对象。

var form_data = new FormData(); 
     var inputs = $(document).find("#file_form input"); 
     $.each(inputs, function (obj, v) { 
      $.each($(v)[0].files, function(i, file) { 
         form_data.append(v.name, file); 
       }); 
     }); 
     form_data.append("status", 'update'); 

我已经更新了小提琴。