Reputation: 595
I'm trying to upload multiple images for an image upload system using AJAX on Jquery.
However, I'm having trouble getting the FormData object to take in the data from the file input. Here is my code:
HTML:
<form id="multiform" role="form" action="process.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<div class="">
<label for="picture">Upload Pictures</label>
<input type="file" id="pic_upload_file" name="pics[]" multiple>
<input type="button" id="pic_upload" name="pic_upload" value="Upload">
</div>
</div>
</form>
JQuery
$('#pic_upload').click(function(e) {
var formData = new FormData();
formData.append("pics", file);
});
This object is created and I can see it in the console, but I dont know how to get the user file input data into it to send to a php script.
Can anyone help?
Upvotes: 1
Views: 11653
Reputation: 318182
You have a file input that takes multiple files, so you have to get those files and append each one to the formData object
$('#pic_upload').on('click', function(e) {
var formData = new FormData(),
files = $('#pic_upload_file').get(0).files;
$.each(files, function(i, file) {
formData.append("pics_" + i, file);
});
$.ajax({
url : 'test.php',
data : formData,
contentType : false,
processData : false,
type : 'POST'
});
});
Upvotes: 2