简体   繁体   中英

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

I am trying send my form fields along with an array of file objects through ajax call. I used the answer from this question to add/choose multiple files. This answer stores files in an array and sends the files as FormData Object, But in my code i have other forms fields also. I am sending those data from ajax using form.serialize() method. Now i have to send the array of file object together with my all the old data.

let files = []

this above array is array of file objects

So i tried this,

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

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

I am using django in the backend, i receive like this,

request.POST.get('filedata')

But using this i receive filedata field as a string "[object FormData]".My question is how to send FormData together with form.serialize()

This is my 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>

I don't want to upload files on clicking upload files button,I want to upload files on clicking submit button together with my text field and files array

If this is not possible how can i send my form fields along with files array to backend?

$('#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
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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