使用dropzone.js发送多个formData时如何发送?

5

dropzone.js的文档/维基没有说明如何发送表单字段。

我刚刚了解了FormData对象,它说明了如何使用表单字段填充对象。问题在于,如果用整个表单填充对象,则无法发送数据,但是如果逐个附加表单字段,它们将会被发送...

以下代码可行:

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);
    });
}

好的,我现在明白了...你是说手动将被接受的文件附加到我的表单中的输入框里面,这个输入框与dropzone.js无关,对吧?我不确定该如何做到这一点,将文件数据附加到一个输入框中。 - Chazy Chaz
2个回答

8

请查看评论...

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());
    });
});

一个循环,我越来越慢了...谢谢! - Chazy Chaz

2
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());
  });
  
  });

}

1
最好使用发送功能而不是发送多个功能,因为用户可能只上传一个文件。 - Isaac Quarshie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接