繁体   English   中英

上传图像后,使用JS调整大小并保存在PHP中,如何使用PHPMAILER通过电子邮件发送调整后的文件?

[英]After uploaded a image, resized with JS and saved in PHP, how do I send the resized file via email using PHPMAILER?

我来自巴西。 所以,对不起我的英语不好。 我将尽力解释我需要什么,我是javascript和php的新手...

我使用的是javascript,它会在上传之前调整图片大小。 好。 之后,我使用php将调整大小的图像保存到服务器。 好。

我现在需要的是...如何获取此调整大小的图像并使用PHPMAILER通过电子邮件发送?

这是代码:

的index.html

<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <title>Cadastro de Foto</title>

    <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <script src="js/canvas-to-blob.min.js"></script>
    <script src="js/resize.js"></script>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

    <script type="text/javascript">

        // Iniciando biblioteca
        var resize = new window.resize();
        resize.init();

        // Declarando variáveis
        var imagens;
        var imagem_atual;

        // Quando carregado a página
        $(function ($) {

            // Quando selecionado as imagens
            $('#imagem').on('change', function () {
                enviar();
            });

        });

        /*
         Envia os arquivos selecionados
         */
        function enviar()
        {
            // Verificando se o navegador tem suporte aos recursos para redimensionamento
            if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
                alert('O navegador não suporta os recursos utilizados pelo aplicativo');
                return;
            }

            // Alocando imagens selecionadas
            imagens = $('#imagem')[0].files;

            // Se selecionado pelo menos uma imagem
            if (imagens.length > 0)
            {
                // Definindo progresso de carregamento
                $('#progresso').attr('aria-valuenow', 0).css('width', '0%');

                // Escondendo campo de imagem
                $('#imagem').hide();

                // Iniciando redimensionamento
                imagem_atual = 0;
                redimensionar();
            }
        }

        /*
         Redimensiona uma imagem e passa para a próxima recursivamente
         */
        function redimensionar()
        {
            // Se redimensionado todas as imagens
            if (imagem_atual > imagens.length)
            {
                // Definindo progresso de finalizado
                $('#progresso').html('Imagen(s) enviada(s) com sucesso');

                // Limpando imagens
                limpar();

                // Exibindo campo de imagem
                $('#imagem').show();

                // Finalizando
                return;
            }

            // Se não for um arquivo válido
            if ((typeof imagens[imagem_atual] !== 'object') || (imagens[imagem_atual] == null))
            {
                // Passa para a próxima imagem
                imagem_atual++;
                redimensionar();
                return;
            }

            // Redimensionando
            resize.photo(imagens[imagem_atual], 800, 'dataURL', function (imagem) {

                // Salvando imagem no servidor
                $.post('ajax/salvar.php', {imagem: imagem}, function() {

                    // Definindo porcentagem
                    var porcentagem = (imagem_atual + 1) / imagens.length * 100;

                    // Atualizando barra de progresso
                    $('#progresso').text(Math.round(porcentagem) + '%').attr('aria-valuenow', porcentagem).css('width', porcentagem + '%');

                    // Aplica delay de 1 segundo
                    // Apenas para evitar sobrecarga de requisições
                    // e ficar visualmente melhor o progresso
                    setTimeout(function () {
                        // Passa para a próxima imagem
                        imagem_atual++;
                        redimensionar();
                    }, 1000);

                });

            });
        }

        /*
         Limpa os arquivos selecionados
         */
        function limpar()
        {
            var input = $("#imagem");
            input.replaceWith(input.val('').clone(true));
        }
    </script>
</head>

<body>

<div class="container">

    <h1>Cadastro de Foto</h1>

    <form method="post" action="#" role="form">

        <div class="progress">
            <div id="progresso" class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="0"
                 aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>
        </div>

        <div class="form-group row">

            <div class="col-xs-12">
                <input id="imagem" type="file" accept="image/*" multiple/>
            </div>

        </div>

    </form>

</div>

</body>
</html>

以下是保存调整大小的文件的php

salvar.php

<?php
   $imagem = $_POST['imagem'];
   list($tipo, $dados) = explode(';', $imagem);
   list(, $tipo) = explode(':', $tipo);
   list(, $dados) = explode(',', $dados);
   $dados = base64_decode($dados);
   $nome = md5(uniqid(time()));
   file_put_contents("../img/{$nome}.jpg", $dados);
 ?> 

好吧。保存了调整大小的文件后,我需要使用phpmailer ..通过电子邮件将此文件发送到我自己的电子邮件地址。

我怎么做 ?? 请帮我

这是resize.js

window.resize = (function () {

'use strict';

function Resize() {
    //
}

Resize.prototype = {

    init: function(outputQuality) {
        this.outputQuality = (outputQuality === 'undefined' ? 0.8 : outputQuality);
    },

    photo: function(file, maxSize, outputType, callback) {

        var _this = this;

        var reader = new FileReader();
        reader.onload = function (readerEvent) {
            _this.resize(readerEvent.target.result, maxSize, outputType, callback);
        }
        reader.readAsDataURL(file);

    },

    resize: function(dataURL, maxSize, outputType, callback) {

        var _this = this;

        var image = new Image();
        image.onload = function (imageEvent) {

            // Resize image
            var canvas = document.createElement('canvas'),
                width = image.width,
                height = image.height;
            if (width > height) {
                if (width > maxSize) {
                    height *= maxSize / width;
                    width = maxSize;
                }
            } else {
                if (height > maxSize) {
                    width *= maxSize / height;
                    height = maxSize;
                }
            }
            canvas.width = width;
            canvas.height = height;
            canvas.getContext('2d').drawImage(image, 0, 0, width, height);

            _this.output(canvas, outputType, callback);

        }
        image.src = dataURL;

    },

    output: function(canvas, outputType, callback) {

        switch (outputType) {

            case 'file':
                canvas.toBlob(function (blob) {
                    callback(blob);
                }, 'image/jpeg', 0.8);
                break;

            case 'dataURL':
                callback(canvas.toDataURL('image/jpeg', 0.8));
                break;

        }

    }

};

return Resize;}());

请尝试以下代码以使用PHPMAILER发送电子邮件:

<?php 
require_once 'class.phpmailer.php';
$mail = new PHPMailer();
// Now you only need to add the necessary stuff

// HTML body

$body = "</pre>
<div>";
$body .= " Hello Dimitrios
";
$body .= "<i>Your</i> personal photograph to this message.
";
$body .= "Sincerely,
";
$body .= "phpmailer test message ";
$body .= "</div>" ;

// And the absolute required configurations for sending HTML with attachement
$fileName = 'path_of_image/image.jpg'; 
$mail->AddAddress("sendemailto@mail.zz", "My-webpage Website");
$mail->Subject = "test for phpmailer-3";
$mail->MsgHTML($body);
$mail->AddAttachment($fileName);
if(!$mail->Send()) {
echo "There was an error sending the message";
exit;
}
echo "Message was sent successfully";

?>

更新的代码

<?php 
    require_once 'class.phpmailer.php';
    $mail = new PHPMailer();
    // Now you only need to add the necessary stuff

    // HTML body

    $imagem = $_POST['imagem'];
    list($tipo, $dados) = explode(';', $imagem);
    list(, $tipo) = explode(':', $tipo);
    list(, $dados) = explode(',', $dados);
    $dados = base64_decode($dados);
    $nome = md5(uniqid(time()));
    file_put_contents("img/{$nome}.jpg", $dados);

    $body = "</pre>
    <div>";
    $body .= " Hello Dimitrios
    ";
    $body .= "<i>Your</i> personal photograph to this message.
    ";
    $body .= "Sincerely,
    ";
    $body .= "phpmailer test message ";
    $body .= "</div>" ;

    // And the absolute required configurations for sending HTML with attachement
    $fileName = 'img/'.$nome.'.jpg'; 
    $mail->AddAddress("sendemailto@mail.zz", "My-webpage Website");
    $mail->Subject = "test for phpmailer-3";
    $mail->MsgHTML($body);
    $mail->AddAttachment($fileName);
    if(!$mail->Send()) {
    echo "There was an error sending the message";
    exit;
    }
    echo "Message was sent successfully";

    ?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM