如何使用 ajax 和资源管理器上传多个文件

how to upload multiple files with ajax and explorer

如何在浏览时使用 ajax 上传多个文件?

这是我的 html:

<p><input class="browse" type="button" value="Browse" onclick="file_explorer();"></p>
<input type="file" id="selectfile" multiple> 

和 js:

function file_explorer() {
        document.getElementById('selectfile').click();
        document.getElementById('selectfile').onchange = function() {
            for (var i=0; i< e.dataTransfer.files.length;i++){ // multiple files
              fileobj = document.getElementById('selectfile').files[i];
              ajax_file_upload(fileobj);
            }
        };
    }

 function ajax_file_upload(file_obj) {
    if(file_obj != undefined) {
        var form_data = new FormData(); 
        form_data.append('file', file_obj);
      $.ajax({

        type: 'POST',
        url: 'ajax.php',
        contentType: false,
        processData: false,
        data: form_data,

        success:function(response) {
          $(".success").html(response);
          $('#selectfile').val('');

        }

      });
    }
  }

下面的这个对 1 个文件工作正常:

function file_explorer() {
        document.getElementById('selectfile').click();
        document.getElementById('selectfile').onchange = function()                 
              fileobj = document.getElementById('selectfile').files[0];
              ajax_file_upload(fileobj);

        };
    }

我尝试了多次,但不幸的是,它不起作用:

function file_explorer() {
        document.getElementById('selectfile').click();
        document.getElementById('selectfile').onchange = function() {
            for (var i=0; i< e.dataTransfer.files.length;i++){
              fileobj = document.getElementById('selectfile').files[i];
              ajax_file_upload(fileobj);
            }
        };
    }

我怎样才能使它对多个文件正常工作?

好的,您的代码出现错误 e 未定义,因此您可以将 e.dataTransfer 更改为 this .. 请参见下面的示例

document.getElementById('selectfile').onchange = function() {
  for (var i=0; i< this.files.length;i++){
    fileobj = document.getElementById('selectfile').files[i];
    console.log(fileobj.name);
    //ajax_file_upload(fileobj);
  }
};
<input type="file" id="selectfile" multiple>

我可以通过对您的代码进行少量更改来实现此功能: 1. e 未定义 - 所以令 e = document.getElementById('selectfile') 2. 将 e.dataTransfer.files.length 替换为 e.files.length