create FormData instance for each file in <input type=file multiple>

前端 未结 2 1129
无人共我
无人共我 2021-01-14 04:20

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 eleme

相关标签:
2条回答
  • 2021-01-14 04:44

    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

    0 讨论(0)
  • 2021-01-14 04:48

    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();
    
    0 讨论(0)
提交回复
热议问题