0

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?

  • 1
    Looks like the same issue in question (45531155).Try this[here] [here]: https://stackoverflow.com/questions/45531155/send-array-of-files-using-ajax – Govi-Boy Jul 22 '20 at 06:33
  • i have gone through this question, they are sending only formdata but i want to send other form fields values like text fields, radio button and select tags along with formdata – santhoshkb Jul 22 '20 at 08:23

1 Answers1

0
$('#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
    })
}
toto
  • 1,180
  • 2
  • 13
  • 30