3

I have following html

<form id="submit-form">
  <input type="file" id="resume" name="resume[]" class="inputFileHidden" multiple>
  <input type="submit">
</form>

I am uploading files using ajax using formdata. The thing is that I don't want to send all files in one go using ajax. Instead I want to send single file per ajax request.

To upload files I am using following jQuery code

$('#submit-form').submit(function(e) {
  e.preventDefault();
  var formData = new FormData(this);
  var url = "upload-files.php";
  $.ajax({
    url: url,
    type: 'post',
    data: formData,
    success: function(response) {
      alert(response);
    },
    cache: false,
    contentType: false,
    processData: false
  })
})
Bhuwan
  • 16,525
  • 5
  • 34
  • 57
Mayank
  • 145
  • 1
  • 11
  • Check this [SO answer](https://stackoverflow.com/a/19296001/1151408), relatively to the for loop. (put the ajax inside it) – Yuri Mar 30 '18 at 08:29

1 Answers1

3

You can just use forEach method of FormData:

$('#submit-form').submit(function(e) {
  e.preventDefault();
  var formData = new FormData(this);
  var url = "upload-files.php";

  formData.forEach(function(entry) {
    if (entry instanceof File) {
      var fileForm = new FormData()
      fileForm.append('resume', entry)

      $.ajax({
        url: url,
        type: 'post',
        data: fileForm,
        success: function(response) {
          alert(response);
        },
        cache: false,
        contentType: false,
        processData: false
      })
    }
  })
})
dfsq
  • 191,768
  • 25
  • 236
  • 258