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?
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?
Share Improve this question edited Jun 29, 2017 at 8:45 linktoahref 8,0023 gold badges32 silver badges53 bronze badges asked Sep 17, 2014 at 15:35 MobazMobaz 5953 gold badges11 silver badges26 bronze badges 1- What exactly is in your file variable? – leopik Commented Sep 17, 2014 at 15:41
1 Answer
Reset to default 2You 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'
});
});