How to send multiple files with Ajax

✔ Recommended Answer

This line:


only appends a single file. As you want to upload the multiple files from the file input, you'll need to append them all.

for (let i = 0; i<this.files.length; ++i) {     fd.append("file[]", this.files[i]) }


Answered By: freedomn-m

Method #2

To send multiple files with AJAX, you can use the FormData API which allows you to easily construct a key-value pair of data that can be sent to the server. Here's an example:


<form id="myForm"> <input type="file" name="file[]" multiple> <button type="submit">Upload</button> </form>

JavaScript with jQuery:

$(document).ready(function(){ $('#myForm').on('submit', function(e){ e.preventDefault(); var formData = new FormData(this); $.ajax({ url: 'upload.php', type: 'POST', data: formData, contentType: false, processData: false, success: function(data){ console.log(data); } }); }); });

In the above example, we create a form with an input of type "file" that allows multiple files to be selected. When the form is submitted, we prevent the default form submission behavior using e.preventDefault(), and then create a new instance of FormData, passing in the form element as an argument. We then make an AJAX request to the server using $.ajax, passing in the URL of the server-side script that will handle the file upload, the type of request (in this case, "POST"), the data to be sent (our FormData object), and two boolean flags to indicate that we do not want jQuery to process our data or set the content type header. Finally, we define a callback function to handle the response from the server.


Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755