Search code examples
jqueryajaxjquery-file-upload

how to upload multiple files with ajax and explorer


How can i upload multiple files with ajax when browsing?

This is my html:

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

And the 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('');

        }

      });
    }
  }

This, below, does work fine for 1 file:

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

        };
    }

For multiple i tried this but unfortunately, it does not work:

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);
            }
        };
    }

How can i make this work properly for multiple files?


Solution

  • Ok, with your code you got the error e is not defined so you can change e.dataTransfer with this .. see an example below

    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>