Upload two files to PHP using an AJAX using two attach buttons

2

I have the following html with two buttons type file

    <label>Adjuntar Recibo de gas escaneado en JPG o PDF</label>    
    <input type='file' name='archivoReciboGas' id='archivoReciboGas' />

    <br></br>   

    <label>Adjuntar Certificado libertad y tradicion en JPG o PDF</label>
    <input type='file' name='archivoCertiLibertad' id='archivoCertiLibertad' />

Here is the ajax that the file sends but only of 1 button, that is to say only that of the cedula, (Upload the cedula)

var inputFileCedula = document.getElementById('archivoCedula');
var file = inputFileCedula.files[0];
var data = new FormData();
data.append('archivo',file);
var url = 'php/subir_cedula.php';

$.ajax
({  
    url:url,
    type:'POST',
    contentType:false,
    data:data,
    processData:false,
    cache:false
});

Here the upload_edula.php that saves the file

<?php
    //PHP QUE SUBE LA CEDULA Y LA GUARDA

    require 'conectar_bd.php';

    $return = Array('ok'=>TRUE);
    $upload_folder ='../archivos_subidos';
    $nombre_archivo = $_FILES['archivo']['name'];
    $tipo_archivo = $_FILES['archivo']['type'];
    $tamano_archivo = $_FILES['archivo']['size'];

    $tmp_archivo = $_FILES['archivo']['tmp_name'];
    $archivador = $upload_folder . '/' . $nombre_archivo;

    if (!move_uploaded_file($tmp_archivo, $archivador)) {

    $return = Array('ok' => FALSE, 'msg' => "Ocurrio un error al subir el archivo. No pudo guardarse.", 'status' => 'error');
    }

    echo json_encode($return);
?>

In what way could you take advantage of the same Ajax to also send the file that is selected from the other button, ie both at the same time.

Currently I have to create a AJAX and a PHP for each button separately

    
asked by Gabriel Uribe Gomez 06.10.2017 в 05:11
source

1 answer

0

If you want to send the two files at the same time then the simplest solution is to take advantage of the object FormData that you have created using a different constructor, indicating the form from which to obtain the data in the following way:

/* Como no conozco el nombre ni el id del formulario, obtengo el primero del DOM */
var data = new FormData(document.forms[0]);
var url = 'php/subir_cedula.php';

$.ajax({  
    url: url,
    type: 'post',
    contentType: false,
    data: data,
    processData: false
});

This code will create the necessary data to send the form and all its data (not just the files) and depending on whether files have been selected or not, the selected files will be uploaded.

On the receiving side you should detect whether or not each of the files has been sent separately:

<?php
/* Muy importante para devolver el resultado correctamente */
header('Content-Type: application/json; charset=utf-8')
require_once 'conectar_bd.php';

/* Almacenamos los errores aquí, ahora podría ser más de uno */
$errores = [];
$upload_folder ='../archivos_subidos';
/* Estos son los campos de archivo que recibiremos */
$campos = [
  'archivoReciboGas',
  'archivoCertiLibertad',
];
/* Repetimos el bucle por cada campo de archivo recibido */
foreach ($campos as $campo) {
  /* Comprobamos que no hubo ningún error durante la subida */
  if (
    isset($_FILES[$campo]['error']) &&
    ($_FILES[$campo]['error'] === 0)
  ) {
    /* ¡OJO! Agujero de seguridad :/ debes filtrar el nombre de archivo
      o fijarlo al identificador de la transacción y, además, comprobar
      que no existe uno que se vaya a sobreescribir */
    if (
      !move_uploaded_file(
        $_FILES[$campo]['tmp_name'],
        $upload_folder . '/' . $_FILES[$campo]['name']
      )
    ) {
      $errores[] = "Ocurrió un error al subir el archivo '$campo'. No pudo guardarse.";
    }
  } else {
    $errores[] = "Ocurrió un error al subir el archivo '$campo'. ¿Demasiado grande?";
  }
}
/* Comprobamos si hubo algún error en el proceso */
if (count($errores) > 0) {
  $return = [
    'ok' => false,
    'msg' => implode("\n", $errores),
    'status' => 'error',
  ];
} else {
  $return = [
    'ok' => true
  ];
}
/* Devolvemos el resultado */
echo json_encode($return);
?>
    
answered by 06.10.2017 в 08:40