-1

i´m traying to do a web application, that i can attach any files into email and insert name in Database.

i can see post in this site about this topic, but i can´t do it.

i have a input multiple that with this i can select any files:

<input type="file" name="adjunto" id="adjunto" multiple>

with jQuery i´m traying get selected files:

var archivo = $("#adjunto").prop('files')[0];
var nombreArchivo = $("#adjunto").val();

this files or file i insert it into a FormData

formData.append('file', archivo);

After send formData to controller with Ajax:

public function setIncidenciaPost(Request $request){


    $uploadedFile = "";
    $filename = "";


    // bloque para adjuntar fichero al email al abrirIncidencia


    if($request->file('file') != ""){

        $uploadedFile = $request->file('file');
        $destino = public_path().'/subidas';

        for($i = 0; $i < count($uploadedFile); $i++){
            $filename = $uploadedFile[$i]->getClientOriginalName();

            $uploadedFile[$i]->move($destino, $filename);
        }


        
    }





    $resultado = \DB::table('incidencias')->insert([
                                                     'fecha_solicitud' => $request["fechaSolicitud"],
                                                     'fecha_respuesta' => $request["fechaRespuesta"],
                                                           'categoria' => $request["categoria"],
                                                           'asignadoA' => $request["tecnico"],
                                                         'solicitante' => $request["solicitante"],
                                                           'prioridad' => $request["prioridad"],
                                                              'estado' => "pendiente",
                                                              'asunto' => $request["asunto"],
                                                              'cuerpo' => $request["mensaje"],
                                                             'cliente' => $request["cliente"],
                                                             'adjunto' => $filename
                                                    ]);

    $idIncidencia = \DB::getPdo()->lastInsertId();

    // ENVIA EMAIL A LOS TÉCNICOS CUANDO SE GENERA LA INCIDENCIA
    $this->enviarEmail($request);

}

When i do var_dump($filename) i can show only one file. If i do var_dump($uploadedFile)

web browser console show this:

 array(1) {
 [0]=>
  object(Illuminate\Http\UploadedFile)#248 (7) {
    ["test":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    bool(false)
    ["originalName":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    string(11) "Captura.PNG"
    ["mimeType":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    string(9) "image/png"
    ["error":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    int(0)
    ["hashName":protected]=>
    NULL
    ["pathName":"SplFileInfo":private]=>
    string(24) "C:\xampp\tmp\phpB785.tmp"
    ["fileName":"SplFileInfo":private]=>
    string(11) "phpB785.tmp"
  }
}

only one file. If in jquery remove index [0] in web broser console show this:

    array(1) {
  [0]=>
  object(Illuminate\Http\UploadedFile)#248 (7) {
    ["test":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    bool(false)
    ["originalName":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    string(11) "Captura.PNG"
    ["mimeType":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    string(9) "image/png"
    ["error":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    int(0)
    ["hashName":protected]=>
    NULL
    ["pathName":"SplFileInfo":private]=>
    string(24) "C:\xampp\tmp\php2397.tmp"
    ["fileName":"SplFileInfo":private]=>
    string(11) "php2397.tmp"
  }
}

i don´t know that i´m doing wrong... thanks for help and sorry for my english

after responses i trayed it:

formData.append('file[]',  document.getElementById('fileToUpload').files[0]);

with this result:

array(1) {
  [0]=>
  object(Illuminate\Http\UploadedFile)#261 (7) {
    ["test":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    bool(false)
    ["originalName":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    string(11) "Captura.PNG"
    ["mimeType":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    string(9) "image/png"
    ["error":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    int(0)
    ["hashName":protected]=>
    NULL
    ["pathName":"SplFileInfo":private]=>
    string(24) "C:\xampp\tmp\php3A08.tmp"
    ["fileName":"SplFileInfo":private]=>
    string(11) "php3A08.tmp"
  }
}

i´m traying select two img but only i can see one

UPDATE

php controller

public function setIncidenciaPost(Request $request){


    $uploadedFile = "";
    $filename = "";


    // bloque para adjuntar fichero al email al abrirIncidencia


    if($request->file('file') != ""){

        $uploadedFile = $request->file('file');
        $destino = public_path().'/subidas';

        for($i = 0; $i < count($uploadedFile); $i++){
            $filename = $uploadedFile[$i]->getClientOriginalName();

            $uploadedFile[$i]->move($destino, $filename);
        }


        
    }





    $resultado = \DB::table('incidencias')->insert([
                                                     'fecha_solicitud' => $request["fechaSolicitud"],
                                                     'fecha_respuesta' => $request["fechaRespuesta"],
                                                           'categoria' => $request["categoria"],
                                                           'asignadoA' => $request["tecnico"],
                                                         'solicitante' => $request["solicitante"],
                                                           'prioridad' => $request["prioridad"],
                                                              'estado' => "pendiente",
                                                              'asunto' => $request["asunto"],
                                                              'cuerpo' => $request["mensaje"],
                                                             'cliente' => $request["cliente"],
                                                             'adjunto' => $filename
                                                    ]);

    $idIncidencia = \DB::getPdo()->lastInsertId();

    // ENVIA EMAIL A LOS TÉCNICOS CUANDO SE GENERA LA INCIDENCIA
    $this->enviarEmail($request);

}

SCRIPT JS that send files to controller:

if(contador == 1){

    /*
    * Tenemos que crear un formData, para enviar el archivo adjunto
    * Una vez creado, debemos añadirle todos los campos del formulario
    * Así los recibiremos en el controlador.
    */

    var fechaSolicitud = $("#fechaSolicitud").val();
    var categoria = $("#categoria").val();
    var prioridad = $("#Abrirprioridad").val();
    var telefono = $("#telefonoContacto").val();
    var asunto = $("#asunto").val();
    var mensaje = $("#cuerpoMensaje").val();
    var token = $("#token").val();
    var archivo = $("#adjunto").prop('files')[0];
    var nombreArchivo = $("#adjunto").val();
    var formData = new FormData();

    formData.append('file[]', archivo);
    formData.append('fechaSolicitud', fechaSolicitud);
    formData.append('categoria', categoria);
    formData.append('prioridad', prioridad);
    formData.append('asunto', asunto);
    formData.append('mensaje', mensaje);
    formData.append('solicitante', codigoSolicitante);
    formData.append('cliente', codigoCliente);
    formData.append('tecnico', tecnicoSeleccionado);
    formData.append('telefono', telefono);

    $.ajax({
        url: "/setIncidencia",
        type: "POST",
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        contentType: false,
        processData: false,   
        cache: false, 
        data: formData,
        success: function(data){
            $("#correcto").show();
            $("#correcto").append("Incidencia Generada");

            //UNA VEZ CREADA LA INCIDENCIA ENVIAMOS EL EMAIL DESDE EL CONTROLADOR Y REDIRECCIONAMOS A:
            window.location.href = "/home";
        },
        error: function(xhr){
            var data = xhr.responseJSON;
            console.log("Error: "+xhr.status);
            $("#error").show();
            $("#error").append("Ha ocurrido un error al crear la incidencia -> Código de Error: " + xhr.status);
        }
    }); 

}// fin if
daviserraalonso
  • 75
  • 1
  • 13
  • You asked about this already yesterday, [attach more than one file into email, laravel](https://stackoverflow.com/questions/64965840/attach-more-than-one-file-into-email-laravel). I don’t see why the discussion can’t be continued there, it doesn’t look like you added much additional info here, or made any significant progress? (Seeing that this doesn’t even use a parameter name with `[]` in it here, it is probably actually rather a step back even.) – CBroe Nov 24 '20 at 09:04
  • Change `formData.append("#adjunto", input)` to `formData.append("adjunto", input)` and change `$uploadedFile[] = $request->file('file');` to $uploadedFile[] = $request->file('adjunto');` Use the same key to retrieve files from request which you used in formData.append – Donkarnash Nov 28 '20 at 11:50
  • Which is line 55 in the `\app\\Http\\Controllers\\incidencias.php` class? – Donkarnash Nov 28 '20 at 12:35
  • Obviously $fname is a string so the error. You can use either $filename (an array) to loop over in for statement or actually you don't need to have another for loop. You can store the file directly after `$uploadedFile[$i]->getClientOriginalName()` by `$uploadedFile[$i]->move($destino, $fname);` – Donkarnash Nov 28 '20 at 12:45
  • `dd($request->adjunto)` as the first line in the controller method and see how many files you get. And keep track of how long the question is becoming - remove the old controller code and the old errors code – Donkarnash Nov 28 '20 at 12:49

3 Answers3

0

You may try to use file[] instead of file:

formData.append('file[]',  document.getElementById('fileToUpload').files[0]);

It will return array with your files data.

  • @TranQuanSon sorry for my delay in replay your response your solution, i can see in web browser console only file... in my question i posted code in console – daviserraalonso Nov 28 '20 at 11:01
0

Try this

public function setIncidenciaPost(Request $request){

    //Get the array of uploaded files from request data or initialise as empty array
    $uploadedFile = $request->input('adjunto', []);

    $filename = [];


    if(count($uploadedFile)){

        $destino = public_path().'/subidas';

        for($i=0; $i<count($uploadedFile); $i++){
            //Validate the uploaded file
            // $uploadedFile[0]->isValid();

            //Get the original filename of uploaded file
            $filename[] = $fname = $uploadedFile[$i]->getClientOriginalName();

            //Store the file
            $uploadedFile[$i]->move($destino, $fname)
        }
        

        echo var_dump($uploadedFile);
        exit();
    }

    //Rest of the code regarding database persistence etc
}

Based on the code of the javascript you updated, make the following change to upload all files. Your current code is appending just one file to formData it seems.

jQuery

$.each($("#adjunto")[0].files,function(key,input){
    formData.append("#adjunto", input);
});

Vanilla Javascript

const uploadedFiles = document.getElementById("#adjunto");
const noOfFilesUploaded = uploadedFiles.files.length;

for(let i = 0; i < uploadedFiles.files.length; i++) {
    formData.append('adjunto', uploadedFiles.files[i];
}
Donkarnash
  • 12,433
  • 5
  • 26
  • 37
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/225266/discussion-on-answer-by-donkarnash-input-type-file-multiple-jquery-laravel). – Bhargav Rao Nov 29 '20 at 00:55
0

My solution is:

if(contador == 1){

        /*
        * Tenemos que crear un formData, para enviar el archivo adjunto
        * Una vez creado, debemos añadirle todos los campos del formulario
        * Así los recibiremos en el controlador.
        */

        var fechaSolicitud = $("#fechaSolicitud").val();
        var categoria = $("#categoria").val();
        var prioridad = $("#Abrirprioridad").val();
        var telefono = $("#telefonoContacto").val();
        var asunto = $("#asunto").val();
        var mensaje = $("#cuerpoMensaje").val();
        var token = $("#token").val();
        var archivo =  $("#adjunto").prop('files');
        var datosFormulario = new FormData();



        for(let i=0; i < document.getElementById('adjunto').files.length; i++){
            datosFormulario.append('adjunto[]', document.getElementById('adjunto').files[i]);
        }


        datosFormulario.append('fechaSolicitud', fechaSolicitud);
        datosFormulario.append('categoria', categoria);
        datosFormulario.append('prioridad', prioridad);
        datosFormulario.append('asunto', asunto);
        datosFormulario.append('mensaje', mensaje);
        datosFormulario.append('solicitante', codigoSolicitante);
        datosFormulario.append('cliente', codigoCliente);
        datosFormulario.append('tecnico', tecnicoSeleccionado);
        datosFormulario.append('telefono', telefono);



        $.ajax({
            url: "/setIncidencia",
            type: "POST",
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
            contentType: false,
            processData: false,   
            cache: false, 
            data: datosFormulario,
            success: function(data){
                $("#correcto").show();
                $("#correcto").append("Incidencia Generada");

                //UNA VEZ CREADA LA INCIDENCIA ENVIAMOS EL EMAIL DESDE EL CONTROLADOR Y REDIRECCIONAMOS A:
                window.location.href = "/home";
            },
            error: function(xhr){
                var data = xhr.responseJSON;
                console.log("Error: "+xhr.status);
                $("#error").show();
                $("#error").append("Ha ocurrido un error al crear la incidencia -> Código de Error: " + xhr.status);
            }
        }); 

    }// fin if

and in controller:

$nombreArchivo = array();
        $destino = public_path().'/subidas';


        // bloque para subir fichero/s a la carpeta subida en public y posterior envio de email

        if($request->file('adjunto') != ""){

            for( $i=0; $i<count($request->file('adjunto')); $i++ ){
                $nombreArchivo[] = $request->file('adjunto')[$i]->getClientOriginalName();
                


                $request->file('adjunto')[$i]->move($destino, $request->file('adjunto')[$i]->getClientOriginalName());
            }
        }
        //fin bloque


        $resultado = \DB::table('incidencias')->insert([
                                                         'fecha_solicitud' => $request["fechaSolicitud"],
                                                         'fecha_respuesta' => $request["fechaRespuesta"],
                                                               'categoria' => $request["categoria"],
                                                               'asignadoA' => $request["tecnico"],
                                                             'solicitante' => $request["solicitante"],
                                                               'prioridad' => $request["prioridad"],
                                                                  'estado' => "pendiente",
                                                                  'asunto' => $request["asunto"],
                                                                  'cuerpo' => $request["mensaje"],
                                                                 'cliente' => $request["cliente"],
                                                                 'adjunto' => implode(',', $nombreArchivo),
                                                        ]);

        $idIncidencia = \DB::getPdo()->lastInsertId();

        // ENVIA EMAIL A LOS TÉCNICOS CUANDO SE GENERA LA INCIDENCIA
        $this->enviarEmail($request);

    }
daviserraalonso
  • 75
  • 1
  • 13