jojacafe
6/7/2017 - 6:48 AM

Files upload attach mail

Files upload attach mail

...
<input type="file" name="arxiu" id="arxiu" multiple>
...

<script>
  $('#afegir_accio').on('click', function () {
    var idCasa = $('#idCasa2').val();
    var idPropietari = $("#idPropietari").val();
    var comentari = $('#comentariAccio').val();
    var gestor = "<?php echo (!empty($row->PRO_idGestor) ? $row->PRO_idGestor : '');?>";
  
    var data = new FormData();
    data.append('idCasa', idCasa);
    data.append('comentari', comentari);
    data.append('idGestor', gestor);
    data.append('idPropietari', idPropietari);
    data.append('tipus', 'accio');
    data.append('contactePropietari', $('#accio_propietari').val());
    data.append('nomContactePropietari', $('#accio_propietari option:selected').text());
  
    var countFiles = document.getElementById('arxiu').files.length;
    for (var i=0; i<countFiles; i++) {
        data.append('arxiu[]', $('#arxiu').prop('files')[i]);
    }
  
    url = 'ajax/afegir_logPropietari.php';
    $.ajax({
        url: url,
        dataType: 'html',
        type: 'post',
        processData: false, // important
        contentType: false, // important
        data: data,
        beforeSend: function () {
            $('#afegir_contacte').attr('disabled', true);
        },
        success: function (responseText) {
            $('#afegir_contacte').attr('disabled', false);
            console.log(responseText);
            //window.location = 'logPropietari.php?codi=' + idPropietari;
        },
        error: function (req, status, err) {
            console.log(err);
        }
    });
    return false;
  });
</script>
// Files
$files = [];
// Create directory uploads at path of project
$uploads_dir = __DIR__ . '/../uploads';
if (!empty($_FILES) && array_key_exists('arxiu', $_FILES)) {
    foreach ($_FILES["arxiu"]["error"] as $key => $error) {
        if ($error == UPLOAD_ERR_OK) {
            $tmp_name = $_FILES["arxiu"]["tmp_name"][$key];
            $name = basename($_FILES["arxiu"]["name"][$key]);

            move_uploaded_file($tmp_name, "$uploads_dir/$name");
            array_push($files, "$uploads_dir/$name");
        }
    }
}

$mail = new PHPMailer();
...
if (count($arxius) > 0) {
    foreach ($arxius as $arxiu) {
        $mail->AddAttachment($arxiu);
    }
}
...

// Delete temp files
if(!empty($files)) {
    foreach ($files as $file) {
        if (file_exists($file)) {
            unlink($file);
        }
    }
}