在 sendingmultiple 上使用 dropzone.js 发送 formData

send formData using dropzone.js on sendingmultiple

dropzone.js documentation/wiki 没有说明如何发送表单字段。

我刚读到 FormData object,它说明了如何使用表单字段填充对象。问题是用整个表单填充对象不会发送数据,但如果我一个接一个地附加表单字段,它们就会被发送...

这个有效:

formData.append('name', jQuery('#name').val());

这不是:

var myForm = document.querySelector('form');
formData = new FormData(myForm);

第一个示例将发送 #name 字段,但第二个示例不会发送任何内容(仅发送文件)。

我怎样才能触发它?我想让 dropzone 将整个表单连同文件一起发送(都在同一个请求中)。

init: function() {
    var myDropzone = this,
        submitButton = document.querySelector("[type=submit]");

    submitButton.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        myDropzone.processQueue();
    });

    myDropzone.on('sendingmultiple', function(data, xhr, formData) {
        // this will get sent
        formData.append('name', jQuery('#name').val());
        // this won't
        var myForm = document.querySelector('form');
        formData = new FormData(myForm);
    });
    myDropzone.on('successmultiple', function(files, response) {
        //window.location.replace("/home");
    });
    myDropzone.on('errormultiple', function(files, response) {
        alert(response);
    });
}

查看评论...

myDropzone.on('sendingmultiple', function(data, xhr, formData) {

    // this will get sent
    formData.append('name', jQuery('#name').val());

    // this won't -- we don't need this rn, we can just use jQuery
    // var myForm = document.querySelector('form');

    // you are overwriting your formdata here.. remove this
    //formData = new FormData(myForm);

    // instead, just append the form elements to the existing formData
    $("form").find("input").each(function(){
        formData.append($(this).attr("name"), $(this).val());
    });
});
init: function() {
  this.on("sending", function(file, xhr, formData) { 

    //formData.append('task_name', jQuery('#task_name').val());

    $("form").find("input").each(function(){
      formData.append($(this).attr("name"), $(this).val());
  });
  
  });

}