Bootstrap 4和Phpmailer表单上传文件

时间:2018-11-13 12:54:39

标签: forms twitter-bootstrap-3 bootstrap-4 phpmailer

我认为实现起来很简单,但我真的不知道从哪里开始。我想要的是人们可以添加图像或其他文件的形式中的一个选项。

我以引导程序形式添加了它:

<!--attachments-->
<div class="form-group">
<label for="attachment">Attachment</label>                                            
<input type="file" class="form-control-file" name="attachmentFile" id="attachmentFile">
</div>

到目前为止,我猜很好。但它不会发送,因为必须在我的phpmailer / send.php文件中添加一些内容。这是我现在使用的脚本:

    <?php
    require 'PHPMailerAutoload.php';

    // Controleren of het formulier is verzonden dmv submit 
    if (isset($_POST['submitted'])) { 

    $errors = array(); // Initialize error array. 

    // Geef hier zoveel mogelijk vereiste velden voor validatie
    //Add attachment
    if(is_array($_FILES)) {
    $mail->AddAttachment($_FILES['attachmentFile']
    ['tmp_name'],$_FILES['attachmentFile']['name']); 
    }

    // Controleer naam 
    if (!preg_match("/^[a-zA-Z]+[a-zA-Z[:space:]]{2,}$/", $_POST['naam'])) { 
      $errors[] = 'Naam'; 
    }

    // Controleer adres 
    if (!preg_match("/^[a-zA-Z[:space:]]{1,}$/", $_POST['straat'])) { 
    $errors[] = 'Adres'; 
    } 

    // Controleer huisnummer
    if (!preg_match("/^[0-9]{1,4}$/", $_POST['huisnummer'])) { 
    $errors[] = 'Huisnummer'; 
    }

    // Controleer postcode
    if (!preg_match("/^[0-9]{4}$/", $_POST['postcode'])) {
    $errors[] = 'Postcode (Cijfers)'; 
    }

    // Controleer postcode letters
    if (!preg_match("/^[a-zA-Z]{2}$/", $_POST['letters'])) {
    $errors[] = 'Postcode (Letters)'; 
    }

    // Controleer woonplaats
    if (!preg_match("/^[a-zA-Z]+[a-zA-Z[:space:]]{2,}$/", $_POST['woonplaats'])) {
    $errors[] = 'Woonplaats'; 
    }

    // Controleer Kengetal 
    if (!preg_match("/^[0]{1}[0-9]{1,3}$/", $_POST['kengetal'])) {
    $errors[] = 'Kengetal'; 
    }

    // Controleer telefoonnummer 
    if (!preg_match("/^[0-9]{6,8}$/", $_POST['telefoon'])) {
    $errors[] = 'Telefoonnummer'; 
    }

    // Controleer e-mail adres 
    if (!preg_match("/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)*\.([a-zA-Z]{2,})$/", $_POST['email'])) { 
      $errors[] = 'E-mail adres'; 
    } 

    // Controleer tekstvak
    if (empty($_POST['bericht'])) { 
      $errors[] = 'Bericht'; 
    } 

    if (empty($errors)) {

    // Voer hier de gegevens in

    $mailFrom = "myEmail";
    $mailTo = "myEmail";
    $senderNaam = $_POST['naam'];
    $senderEmail = $_POST['email']; 
    $subject = 'mySubject';

    $okMessage = '<p>blablabla</p>';
    $errorMessage = '<p>blablabla</p>';

    $emailText .= "Naam: " . $_POST['titel']." ". $_POST['naam']. "\n";
    $emailText .= "Bedrijfsnaam: " . $_POST['bedrijfsnaam']. "\n";
    $emailText .= "Adres: " . $_POST['straat']." ". $_POST['huisnummer']." ". $_POST['toevoeging']. "\n";
    $emailText .= "Postcode: " . $_POST['postcode']." ". $_POST['letters']. "\n";
    $emailText .= "Woonplaats: " . $_POST['woonplaats']. "\n";
    $emailText .= "Telefoonnummer: " . $_POST['kengetal']." ". $_POST['telefoon']. "\n";
    $emailText .= "E-mailadres: " . $_POST['email']. "\n";
    $emailText .= "Bericht: " . $_POST['bericht']. "\n";

    $mail = new PHPMailer;
    $mail->CharSet = 'UTF-8';
    $mail->isSMTP();                                    // Set mailer to use SMTP
    $mail->Host = 'SMTP SERVER';            // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                             // Enable SMTP authentication
    $mail->Username = 'User';               // SMTP username
    $mail->Password = 'Pass';                        // SMTP password
    $mail->SMTPSecure = 'ssl';                          // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 465;                                   // TCP port to connect to


    $mail->Sender = $mailFrom;
    $mail->SetFrom($senderEmail, $senderNaam);
    $mail->AddReplyTo($senderEmail, $senderNaam);
    $mail->Subject = $subject;
    $mail->MsgHTML($emailText);
    $mail->AddAddress($mailTo, $mailTo);
    $mail->addAttachment($uploadfile, 'My uploaded file'); **// ADDED THIS HERE**


    $mail->isHTML(true);                                // Set email format to HTML

    $mail->Subject = $subject;
    $mail->Body    = "<table>
                <tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Naam:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['titel']." ".$_POST['naam']."</td></tr>
                <tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Bedrijfsnaam:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['bedrijfsnaam']."</td></tr>
                <tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Adres:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['straat']." ".$_POST['huisnummer']." ".$_POST['toevoeging']."</td></tr>
                <tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Postcode:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['postcode']." ".$_POST['letters']."</td></tr>
                <tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Woonplaats:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['woonplaats']."</td></tr>
                <tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Telefoonnummer:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['kengetal']." ".$_POST['telefoon']."</td></tr>
                <tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>E-mailadres:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['email']."</td></tr>
                <tr><td style='padding-left: 10px; padding-right: 10px; background: #eee;'>Bericht:</td><td style='padding-left: 10px; font-weight: bold;'>".$_POST['bericht']."</td></tr>
                </table>";

    $mail->AltBody = $emailText;

    if(!$mail->send()) {
            $responseArray = array('type' => 'danger', 'message' => $errorMessage);
        } else {
            $responseArray = array('type' => 'success', 'message' => $okMessage);
            }
        }

    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        $encoded = json_encode($responseArray);

        header('Content-Type: application/json');

        echo $encoded;
        } else {
        echo $responseArray['message'];
        }

    }
    ?>

还将此添加到<form> enctype =“ multipart / form-data”

编辑#2:我也有一个与此相关的contact.js文件:

data: $(this).serialize(), 我在此更改了它: data: new FormData(this), 因为我在某处读到这可能是问题所在,但这没有道理。

1 个答案:

答案 0 :(得分:0)

好的,表格正在发送附件!我希望只有一点点小事情,我希望有人可以帮助我。首先是代码。

在contact.js中-我不得不将data: $(this).serialize(),更改为data: new FormData(this),

    $(function () {

        $('#contact-form').validator();

        $('#contact-form').on('submit', function (e) {
            if (!e.isDefaultPrevented()) {
                var url = "send.php";

                $.ajax({
                    type: "POST",
                    url: url,
                    data:  new FormData(this),
                    cache       : false,
                    contentType : false,
                    processData : false,
                    success: function (data)
                    {
                        var messageAlert = 'alert-' + data.type;
                        var messageText = data.message;

                        var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
                        if (messageAlert && messageText) {
                            $('#contact-form').find('.messages').html(alertBox);
                            $('#contact-form')[0].reset();  //Remove this line if form should not reset after submit
                            $('body, html').animate({scrollTop:$('#contact-form').offset().top}, 'fast'); //Remove this line if form should not scroll to top of the form after submit
                        }
                    }
                });
                return false;
            }
        })
    });

Myform.html-2件事:enctype="multipart/form-data"中的<form>

    <!--attachments-->
      <div class="form-group">
        <label for="attachment">Attachment</label>                                            
        <input type="file" class="form-control-file" name="attachmentFile" id="attachmentFile">
      </div>

在表单中所需的某个位置。

最后将其放在您的phpmailer文件中:

    //Add attachment
    if(is_array($_FILES)) {
        $mail->AddAttachment($_FILES['attachmentFile']['tmp_name'],$_FILES['attachmentFile']['name']); 
    }

我在$mail->AddAddress($mailTo, $mailTo);下做了

到目前为止,如何解决此问题。一开始我还提到一个问题。

data: new FormData(this),,当我点击send并且表单停留在同一页面时,我仍然收到okMes​​sage(带有标记)。

使用 data: new FormData(this),,它会转到一个新页面,并且只给出黑白纯文本(不带标记)。 因此,它像FormData否决了某些事情。希望有人可以帮助我。

编辑:似乎我也已解决此问题。放在这里。

cache       : false,
contentType : false,
processData : false,

..下面data: new FormData(this),