I'm trying to make an image uploader with PHP and JavaScript (jQuery using $.ajax).
HTML:
<form method="post" action="php/inc.publicar.php" id="publicacion" enctype="multipart/form-data">
<input type="file" id="file" name="file[]" accept="image/*" multiple />
<p id="estado"></p>
</form>
JS:
var files;
$('#file').on('change', subiendoImagenes);
function subiendoImagenes(event) {
files = event.target.files;
event.stopPropagation();
event.preventDefault();
var fileSize = $(this).get(0).files[0].size;
if (fileSize < 2097152) {
var data = new FormData();
$.each(files, function(key, value) {
data.append('file', value);
});
$.ajax({
url: 'php/inc.uploadFile.php',
cache: false,
contentType: false,
processData: false,
type: 'post',
data: data,
beforeSend: function() {
$('#estado').html('Subiendo imagen por favor espere...');
},
success: function(data, textStatus, jqXHR) {
if(typeof data.error === 'undefined') {
$('#estado').html(data);
} else {
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('ERRORS: ' + textStatus);
}
});
} else {
$('#estado').html('El peso de la imagen que intenta subir, excede los <strong>2MB</strong>')
}
}
PHP:
$errors = 0;
if(isset($_POST) && $_SERVER["REQUEST_METHOD"] == "POST") {
if (array_key_exists('file', $_FILES)) {
$image = $_FILES["file"]["name"];
$imagenSubida = $_FILES['file']['tmp_name'];
$max_file_size = 2097152; // 2 MB
foreach ($image as $f => $name) { // Line of error
// all code here works correctly
} // Fin Foreach
} else { echo 'Error inesperado.'; }
}
I think the problem is in the JavaScript. I think when you submit the files, it sends only one.
**var_dump($_FILES) uploading 3 files: **
Why is it not sending all the files?
