选择并将多个文件上传到ajax

时间:2016-10-31 13:43:49

标签: javascript html ajax forms

我希望能够选择一系列图像,然后通过ajax调用上传数据。下面是我的HTML。我无法将文件附加到for循环中。

 <form name="nameform" method="POST" enctype="multipart/form-data">
    <input id="file_input" type="file" name="files[]" multiple>     
    <input type="button" name="button" value="Submit" onClick="getInfo(this.form)" />
 </form>


  var oMyForm = new FormData();
  var filelenth = file_input.files;
  for (var i = 0; i < filelenth.length; i++) {
    var fileCheck = file_input.files[i];
    if (!fileCheck.type.match('image.*')) {
      continue;
    }
    oMyForm.append('files[]', fileCheck, fileCheck.name);
  }

  $.ajax({
    url: 'URL',
    data: oMyForm,
    dataType: 'json',
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(data) {
      alert(data);
    }
  });

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

 var data2 = new FormData();
    $.each($("#attachmentInfo :file"), function(i, file) {
        data2.append('attachmentFiles', file.files[0]);
    });

        $.ajax({
            type: 'POST',
            contentType: false,
            processData: false,
            dataType: 'text',
            url: 'savefile2.html',
            data: data2,
            success: function(responseData, textStatus) {

            },
            complete: function(textStatus) {

            },
            error: function(responseData)
            {

            }
        });