Reputation: 47
I'm trying to upload multiple files in a single input field. So far, the code works but it's just sending the first file to the upload.php file. I'm using jQuery.
HTML:
<input id="carica" type="file" name="carica[]" multiple="true"/>
<button type="button" id="upload_sub" class="button">Carica</button>
JavaScript:
$("#upload_sub").click(function() {
$.ajax({
url: "./src/upload.php",
type: "POST",
contentType: false,
processData: false,
data: function() {
var data = new FormData();
data.append("carica", $("#carica").get(0).files[0]);
return data;
// Or simply return new FormData(jQuery("form")[0]);
}(),
error: function(_, textStatus, errorThrown) {
alert("Error");
console.log(textStatus, errorThrown);
},
success: function(response, textStatus) {
alert("Success");
console.log(response, textStatus);
}
});
});
PHP:
print_r ($_FILES);
Output:
Array
(
[carica] => Array
(
[name] => prova.pdf
[type] => application/pdf
[tmp_name] => /tmp/phpvIlTeL
[error] => 0
[size] => 7234
)
)
success
Upvotes: 1
Views: 118
Reputation: 97672
Loop through the entire file list and send all the files
data: function() {
var data = new FormData();
var files = $("#carica").get(0).files;
for (var i = 0; i < files.length; i++){
data.append("carica[]", files[i]);
}
return data;
}(),
Upvotes: 1