jqueryajaxfile-uploadasyncfileupload

Multiple file upload javascript


I have a multiple files upload form that is triggered with button. I'm trying to upload selected files one by on with ajax to create individual progress bars.

I create this event $(document).on("change", "#upload_files", (e) =>{}); but its only work for first file.

I have tried this but FileList always is empty, also this but if user upload more than one file web service return 503 error.

I would't like to use any external plugin because I would like to learn how it works.

var count = 0;

$(document).on("change", "#upload_files", function(e) {
  if(typeof this.files[count] === 'undefined'){
    return false; 
  }
    
  let form_data = new FormData();
  form_data.append('file', this.files[count]);
  form_data.append('folderID', open_folder);
    
  $.ajax({
    'url':'/domain/files.upload_file',
    'type':'POST',
    'data': form_data,
    'contentType': false,
    'processData': false,
    'success': function(){
       count++;
    }
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/js/bootstrap.min.js"></script>

<button onclick="$('#upload_files').click()">Open file</button>

<input type="file" id="upload_files" class="d-none" multiple/>

CodePen example with contextmenu


Solution

  • You're uploading only one file when the change event occurs and it only occurs once per selection not once per file selected.
    Below I loop through the file list and upload each one, one after the other.

    $(document).on("change", "#upload_files", async function(e) {
    
      for (let x = 0; x < this.files.length; x++){
        
        let form_data = new FormData();
        form_data.append('file', this.files[x]);
        form_data.append('folderID', 'open_folder');
        await $.ajax({
          'url':'/domain/files.upload_file',
          'type':'POST',
          'data': form_data,
           'contentType': false,
          'processData': false
        }).catch(e=>console.log(e));
      }
    });