I'm new working with files and I want to upload multiple files in this case images using just one input type file
but this input isn't inside a form
tag, this work when i click on a button
<input type="file" class="form-control" id="imagenArticulo" multiple="multiple">
when my images are selected I press the button and do this
$('#guardarArticulo').click(function(e) {
e.preventDefault();
let imagen = $('#imagenArticulo').prop('files');
console.log(imagen);
let form_data = new FormData();
form_data.append('imagen', imagen);
$.ajax({
type: 'post',
cache: false,
contentType: false,
processData: false,
url: '../includes/productos/guardar_producto.php',
data: form_data,
dataType: 'json',
beforeSend: function() {
},
success: function(respuesta) {
console.log(respuesta);
if (respuesta.tipo == 0) {
window.location.reload(true);
}
if (respuesta.tipo == 1) {
//do soemthing
}
}
});
});
The first console.log
of the variable imagen
after click show this
And finally with PHP when try to process them I do this
if (!is_null($_FILES['imagen']['name'])) {
if ($_FILES['file']['error'] == 0) {
if (!is_dir($ruta)) {
mkdir($ruta);
mkdir($ruta . '/original');
mkdir($ruta . '/thumbnail');
}
$numero_de_imagenes = count($_FILES['imagen']['tmp_name']);
for ($i = 0; $i < $numero_de_imagenes; $i++) {
$imagen = $_FILES['imagen']['name'][$i];
$img_tmp = $_FILES['imagen']['tmp_name'][$i];
$formato = strtolower(pathinfo($imagen, PATHINFO_EXTENSION));
if (in_array($formato, $formatos_validos)) {
$ext_tmp = explode('.', $imagen);
$imagen = sha1($imagen.$random) . '.' . end($ext_tmp);
$ruta = $ruta . '/original/' . $imagen;
move_uploaded_file($img_tmp, $ruta);
list($ancho, $alto) = getimagesize($ruta);
if ($_FILES['imagen']['size'][$i] > 524288 || $ancho > 500 || $alto > 500) {
comprimir($imagen, $fuente, $fuente, 500, 500, 90);
}
comprimir($imagen, $fuente, $destino, 100, 100, 90);
}
}
}
}
I have been with this code before but just for one file, the new part was add the for
loop to it, but when i press click the ajax response is not showing nothing, is not displaying errors or something, I would like to know what i'm missing or doing wrong, algo before the code I tried to print $_FILES['imagen']
to see if it has content but dont show nothing, I hope you can help me, thanks.