create FormData instance for each file in <inpu

2019-02-19 11:29发布

问题:

I'm trying to use input file with multiple attribute and to have the formData split so I would have a formData isnatce for each file in the multiple file element.

HTML

<input type="file" name="file" multiple></label>

JS

new FormData(formElement) // <--- Need to have this for each file selected

I need this because I'm using Cloudinary API and they only accept one file at a time, so I need to send multiple Ajax requests and for each, I need formData instance for each of the files selected, but the problem is, FormData accepts as an argument the how form element, and I cannot separate the files.

DEMO PAGE

回答1:

You can use $.when(), $.map() to append each File of <input type="file"> FileList to new FormData instance, then call $.ajax() for each FormData() instance.

Note, substituted .on() for onsubmit event attribute. Without required attribute or a default .value set name="cloud_name" and name="upload_preset" <input type="text"> elements .value could be an empty string when form submit event occurs.

$(function() {
  var form = $("form");
  form.on("submit", function(e) {
    e.preventDefault();
    var cloudName = $('input[name="cloud_name"]').val(),
      presetName = $('input[name="upload_preset"]').val(),
      URL = "https://api.cloudinary.com/v1_1/" + cloudName + "/image/upload",
      input = form.find("[name=file]");

    $.when.apply($, $.map(input[0].files, function(file, index) {
      var data = new FormData(form[0]);
      data.append("upload_preset", file, file.name);
      return $.ajax({
        type: 'post',
        url: URL,
        data: data,
        processData: false,
        contentType: false,
        cache: false
      });
    }))
    .then(function(response) {
      console.log(response)
    })
    .catch(function(err) {
      console.log(err)
    })
  })
})

plnkr http://plnkr.co/edit/7l0obsusqXVlommdd49L?p=preview



回答2:

Each time you make a formData object you can append to it data like this:

data.append("file", document.getElementById(file).files[0]);

but instead of 0 in for loop you can put loop index and send data to ajax.

and you should initialize data by following :

 var data = new FormData();