0

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

1 Answer 1

1

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));
  }
});
Sign up to request clarification or add additional context in comments.

3 Comments

I try to use your code but input file is not opening. I add $('#upload_files').click(); inside of $(document).on("click", "#upload", function(e) {}) but when I print var file is empty.
This is codepen example of what I have right now.
@cplaiuu I didn't understand the question before, I've changed my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.