繁体   English   中英

如何使用表单序列化()通过 ajax 发送文件对象数组?

[英]How to send array of file objects through ajax with form serialize()?

我正在尝试通过 ajax 调用发送我的表单字段以及文件对象数组。 我使用这个问题的答案来添加/选择多个文件。 这个答案将文件存储在一个数组中,并将文件作为 FormData Object 发送,但在我的代码中,我还有其他 forms 字段。 我使用 form.serialize() 方法从 ajax 发送这些数据。 现在我必须将文件 object 的数组连同我所有的旧数据一起发送。

let files = []

上面的这个数组是文件对象的数组

所以我尝试了这个,

$('#myform').submit(function () {
    var formData = new FormData();
    files.forEach(file => {
        formData.append('file', file);
    });

    $.ajax({
      type: "POST",
      url: url,
      data: form.serialize() + "&filedata=" + formData,
      ...
      ...
    })
}

我在后端使用 django,我收到这样的,

request.POST.get('filedata')

但是使用这个我接收filedata字段作为字符串“[object FormData]”。我的问题是如何将FormData与form.serialize()一起发送

这是我的 html:

<form method="POST" action="/" id="myform">
    <input type="text" name="name"/>
    ...
    <input type="checkbox" id="option1"/>
    <label for="option1">Option 1</label>
    ...
    <select>
        <option>Option 1</option>
        <option>Option 2</option>
    </select>
    ...
    <!--like above checkbox and select elements i have so many other form fields-->
    <!--i want to send files array with all the data from above form elements-->
    
    <input id="myInput" type="file" name="files" multiple style="display:none" />
    <button id="myButton" type="button">Add Files</button>
    <!-- <button id="mySubmitButton" type="button">Upload Files</button> this button is not 
    required as i want upload files on clicking submit -->
    <div id="myFiles"></div>
    <input type="submit" />
</form>

我不想在单击上传文件按钮时上传文件,我想在单击提交按钮时上传文件以及我的文本字段和文件数组

如果这是不可能的,我如何将表单字段与文件数组一起发送到后端?

$('#myform').submit(function () {
    var formData = new FormData();
    $.each($('#myform')[0].files, function(i, file) {
    formData.append('file-'+i, file);
     });

    $.ajax({
      type: "POST",
      url: url,
      data: formData,
      cache: false,
      contentType: false,
      processData: false,
      method: 'POST',
      type: 'POST' // jQuery < 1.9
    })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM