Принимает данные от php и phpmailer - PullRequest
0 голосов
/ 26 февраля 2020

У меня есть форма, и я добавил изменение размера в свое изображение. Проблема в том, как взять уменьшенное изображение из phpmailer. потому что теперь отправляемое изображение - это изображение в полном размере. что мне нужно изменить в phpmailer, чтобы сделать изображение небольшого размера? Я пытался переместить name = "menu1" рядом с, но форма выдает ошибку

async function compressImage (event, useWebWorker) {
    var file = event.target.files[0]
    var logDom
    if (useWebWorker) {
      logDom = document.querySelector('#web-worker-log')
    } else {
      logDom = document.querySelector('#main-thread-log')
    }
    document.getElementById('preview').src = URL.createObjectURL(file)

    logDom.innerHTML = 'Source image size:' + (file.size / 1024 / 1024).toFixed(2) + 'mb'
    console.log('input', file)
    console.log('ExifOrientation', await imageCompression.getExifOrientation(file))
    var options = { maxSizeMB: 1, maxWidthOrHeight: 1024, useWebWorker: useWebWorker }
    const output = await imageCompression(file, options)
    logDom.innerHTML += ', output size:' + (output.size / 1024 / 1024).toFixed(2) + 'mb'
    console.log('output', output)
    const downloadLink = URL.createObjectURL(output)
    logDom.innerHTML += '&nbsp;<a href="' + downloadLink + '" download="' + file.name + '">download compressed image</a>'
    document.getElementById('preview-after-compress').src = downloadLink
    // await uploadToServer(output)
  }

  function uploadToServer (file) {
    var formData = new FormData()
    formData.append('image', file)
    return fetch('http://localhost/image-upload-api', {
      method: 'POST',
      body: formData
    })
  }
</script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/browser-image-compression@1.0.6/dist/browser-image-compression.js">
	<style>
    table, th, td {
        border: 0px solid black;
        border-collapse: collapse;
    }
    td {
        vertical-align: top;
        width: 0%;
    }
    img {
        max-width: 0%;
    }
</style>
			<div class="form-group was-validated">
								<label class="control-label">Menu1</label>
								<input type="file" id="web-worker" name="menu1" accept=".jpg,.jpeg,.pdf,.png" onchange="compressImage(event, true)" required>
								<p id="web-worker-log"></p>
							</div>
							<div class="progress">
								<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
							</div>
							<table>
    <tr>
   
    </tr>
    <tr>
        <td><img id="preview" /></td>
        <td><img id="preview-after-compress"  /></td>
    </tr>
								
</table>

<?php

    $nome        = $_POST["nome-locale"];
    $email       = $_POST["email"];
    $telefono    = $_POST["telefono"];
    $indirizzo   = $_POST["indirizzo"];
    $civico      = $_POST["civico"];
    $citta       = $_POST["citta"];
    $provincia   = $_POST["provincia"];
    $cap         = $_POST["cap"];
    $titolare    = $_POST["titolare"];
	$cf          = $_POST["codice_fiscale"]; 
    $declaration = isset($_POST["declaration"]) ? $_POST['declaration'] : 'No';
    $newsletter  = isset($_POST["newsletter"]) ? $_POST['newsletter'] : 'No';
    $data        = date('d-m-Y'); 


    $body = "<br>nome-locale:" . $nome . "<br>Email:" . $email . "<br>TelefonoLocale:" . $telefono . "<br>Indirizzo:" . $indirizzo . "<br>Civico:" . $civico . "<br>Città:" . $citta . "<br>Provincia:" . $provincia . "<br>Cap:" . $cap . "<br>Nome titolare:" . $titolare . "<br>CF:" . $cf . "<br>Declaration:" . $declaration . "<br>newsletter:" . $newsletter;


    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;

    require 'PHPMailer/src/Exception.php';
    require 'PHPMailer/src/PHPMailer.php';
    require 'PHPMailer/src/SMTP.php';
    // Instantiation and passing `true` enables exceptions
    $mail = new PHPMailer(true);

    $mail->isSMTP(); // Send using SMTP
    $mail->Host       = 'x'; // Set the SMTP server to send through
    $mail->SMTPAuth   = true; // Enable SMTP authentication
    $mail->Username   = 'x'; // SMTP username
    $mail->Password   = 'x'; // SMTP password
    $mail->SMTPSecure = 'x'; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
    $mail->Port       = x; // TCP port to connect to

    if (array_key_exists('menu1', $_FILES) && array_key_exists('menu2', $_FILES)) {
        try {
            //Server settings
            // First handle the upload
            // Don't trust provided filename - same goes for MIME types
            // See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation
            $menu1_filename = $_FILES['menu1']['name'];
            $menu2_filename = $_FILES['menu1']['name'];

            $menu1 = tempnam(sys_get_temp_dir(), hash('sha256', $menu1_filename));
            $menu2 = tempnam(sys_get_temp_dir(), hash('sha256', $menu2_filename));

            if (move_uploaded_file($_FILES['menu1']['tmp_name'], $menu1) &&
                move_uploaded_file($_FILES['menu2']['tmp_name'], $menu2)) {
                // Upload handled successfully
                // Now create a message
                //Recipients
                $mail->setFrom('feed@vaimenu.it', $data);
                $mail->addAddress('feed@vaimenu.it'); // Add a recipient
                $mail->isHTML(true); // Set email format to HTML
                $mail->Subject = ('Iscrizione: ' . $nome);
                $mail->Body = $body;
                $mail->AltBody = 'Iscrizione ricevuta da landing page';

                // Attach the uploaded file
                $mail->AddAttachment($menu1, $menu1_filename);
                $mail->AddAttachment($menu2, $menu2_filename);
                $mail->send();

                $mail->ClearAllRecipients();
                $mail->clearAddresses();
                $mail->ClearAttachments();

                $mail->isHTML(true);
                $mail->Subject = ('Benvenuto, ' . $nome);
                $mail->setFrom('feed@vaimenu.it', 'Vaimenu.it');
                $mail->addAddress($email);

                $message = file_get_contents('Benvenuto.html');
                $message = str_replace('%Nome%', $nome, $message);

                $mail->MsgHtml($message);

                if (!$mail->send()) {
                    $response['error']   = true;
                    $response['message'] = "Message could not be sent. Some thing went wrong Mailer Error: " . $mail->ErrorInfo;
                } else {
                    $response['success'] = true;
                }
            } else {
                $response['error']   = true;
                $response['message'] = 'Failed to move file to ' . $menu1;
            }

            echo json_encode($response);
        } catch (Exception $e) {
            $response['error']   = true;
            $response['message'] = "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";

            echo json_encode($response);
        }
    }
?>

1 Ответ

0 голосов
/ 26 февраля 2020

Вы можете сжать изображение перед отправкой по электронной почте, например:

$target = "./img/".basename($_FILES['fileuploaded']['name']);   
compressedImage($_FILES['fileuploaded']['tmp_name'],$target,75); //75 is quality of image
function compressedImage($source, $path, $quality) {

            $info = getimagesize($source);

            if ($info['mime'] == 'image/jpeg'){
                $image = imagecreatefromjpeg($source);

            }elseif ($info['mime'] == 'image/gif'){
                $image = imagecreatefromgif($source);

            }elseif ($info['mime'] == 'image/png'){ 
                $image = imagecreatefrompng($source);
            }

            imagejpeg($image, $path, $quality);
            return $path;

    }
...