如何使用单个附件选项构建联系人表单以选择“多个附件”选项

时间:2015-12-14 14:50:28

标签: javascript php jquery contact-form

我的联系表单有些麻烦,我想添加选项以选择多个附件。请帮我重建一下。使用单一选择附件一切正常,但我不知道如何添加多附件选项。

PHP代码:

<?php
if($_POST)
{
    $to_Email       = "MyDomain"; //Replace with recipient email address
    $from_Email     = "MyDomain"; //From email address (eg: no-reply@YOUR-DOMAIN.com)
    $subject        = 'MyDomain'; //Subject line for emails

    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

        //exit script outputting json data
        $output = json_encode(
        array(
            'type'=>'error', 
            'text' => 'Request must come from Ajax'
        ));

        die($output);
    } 

    //check $_POST vars are set, exit if any missing
    if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userPhone"]) || !isset($_POST["userMessage"]) || !isset($_POST["userMarka"]) || !isset($_POST["userModel"]) || !isset($_POST["userRocznik"]) || !isset($_POST["userCena"]))
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Puste pole w formularzu.'));
        die($output);
    }

    //Sanitize input data using PHP filter_var().
    $user_Name        = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
    $user_Email       = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
    $user_Phone       = filter_var($_POST["userPhone"], FILTER_SANITIZE_STRING);
    $user_Message     = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
    $user_Marka        = filter_var($_POST["userMarka"], FILTER_SANITIZE_STRING);
    $user_Model       = filter_var($_POST["userModel"], FILTER_SANITIZE_EMAIL);
    $user_Rocznik       = filter_var($_POST["userRocznik"], FILTER_SANITIZE_STRING);
    $user_Cena     = filter_var($_POST["userCena"], FILTER_SANITIZE_STRING);


    $mail_body       .= "\r\n\r\nWiadomość od Sprzedającego - Szczegóły Oferty: "; //sender name
    $mail_body        = $user_Message;
    $mail_body       .= "\r\n\r\nImię i Nazwisko Klienta: ".$user_Name; //sender name
    $mail_body       .="\r\nE-Mail Klienta: ".$user_Email; //sender email
    $mail_body       .="\r\nNumer Telefonu: ".$user_Phone; //sender phone
    $mail_body       .= "\r\n\r\nMarka Pojazdu: ".$user_Marka; //sender marka
    $mail_body       .="\r\nModel Pojazdu: ".$user_Model; //sender model
    $mail_body       .="\r\nRocznik Pojazdu: ".$user_Rocznik; //sender rocznik
    $mail_body       .="\r\nCena Pojazdu: ".$user_Cena; //sender rocznik
    $mail_body       .="\r\n\r\n";

    //additional php validation
    if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Imię i Nazwisko jest zbyt krótkie lub pole jest puste'));
        die($output);
    }
    if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Wprowadź poprawny adres e-mail!'));
        die($output);
    }
    if(!is_numeric($user_Phone)) //check entered data is numbers
    {
        $output = json_encode(array('type'=>'error', 'text' => 'W polu "Telefon" dopuszczalne są tylko cyfry'));
        die($output);
    }

    if(strlen($user_Marka)<2) // If length is less than 4 it will throw an HTTP error.
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Wprowadź Marke Pojazdu!'));
        die($output);
    }

    if(strlen($user_Model)<2) // If length is less than 4 it will throw an HTTP error.
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Wprowadź Model Pojazdu!'));
        die($output);
    }

    if(!is_numeric($user_Rocznik)) //check entered data is numbers
    {
        $output = json_encode(array('type'=>'error', 'text' => 'W polu "Rocznik" dopuszczalne są tylko cyfry'));
        die($output);
    }

    if(!is_numeric($user_Cena)) //check entered data is numbers
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Wprowadź Cene Pojazdu'));
        die($output);
    }
    if(strlen($user_Message)<12) //check emtpy message
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Zbyt krótki opis oferty!'));
        die($output);
    }

### Attachment Preparation ###
$file_attached = false; //initially file is not attached

if(isset($_FILES['file_attach'])) //check uploaded file
{
    //get file details we need
    $file_tmp_name    = $_FILES['file_attach']['tmp_name'];
    $file_name        = $_FILES['file_attach']['name'];
    $file_size        = $_FILES['file_attach']['size'];
    $file_type        = $_FILES['file_attach']['type'];
    $file_error       = $_FILES['file_attach']['error'];

    //exit script and output error if we encounter any
    if($file_error>0)
    {
        $mymsg = array( 
        1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini", 
        2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form", 
        3=>"The uploaded file was only partially uploaded", 
        4=>"No file was uploaded", 
        6=>"Missing a temporary folder" ); 

        $output = json_encode(array('type'=>'error', 'text' => $mymsg[$file_error]));
        die($output); 
    }

    //read from the uploaded file & base64_encode content for the mail
    $handle = fopen($file_tmp_name, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $encoded_content = chunk_split(base64_encode($content));

    //now we know we have the file for attachment, set $file_attached to true
    $file_attached = true;
}



if($file_attached) //continue if we have the file
{
    # Mail headers should work with most clients (including thunderbird)
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion()."\r\n";
    $headers .= "From:".$from_Email."\r\n";
    $headers .= "Subject:".$subject."\r\n";
    $headers .= "Reply-To: ".$user_Email."" . "\r\n";
    $headers .= "Content-Type: multipart/mixed; boundary=".md5('boundary1')."\r\n\r\n";

    $headers .= "--".md5('boundary1')."\r\n";
    $headers .= "Content-Type: multipart/alternative;  boundary=".md5('boundary2')."\r\n\r\n";

    $headers .= "--".md5('boundary2')."\r\n";
    $headers .= "Content-Type: text/plain; charset=utf-8\r\n\r\n";
    $headers .= $mail_body."\r\n\r\n";

    $headers .= "--".md5('boundary2')."--\r\n";
    $headers .= "--".md5('boundary1')."\r\n";
    $headers .= "Content-Type:  ".$file_type."; ";
    $headers .= "name=\"".$file_name."\"\r\n";
    $headers .= "Content-Transfer-Encoding:base64\r\n";
    $headers .= "Content-Disposition:attachment; ";
    $headers .= "filename=\"".$file_name."\"\r\n";
    $headers .= "X-Attachment-Id:".rand(1000,9000)."\r\n\r\n";
    $headers .= $encoded_content."\r\n";
    $headers .= "--".md5('boundary1')."--"; 
}else{
    # Mail headers for plain text mail
    $headers = 'From: '.$from_Email.'' . "\r\n" .
    'Reply-To: '.$user_Email.'' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
}

//send the mail
$sentMail = mail($to_Email, $subject, $mail_body, $headers);

if(!$sentMail) //output success or failure messages
{
    $output = json_encode(array('type'=>'error', 'text' => 'Wiadomość nie mogła zostać wysłana! Przepraszamy!'));
    die($output);
}else{
    $output = json_encode(array('type'=>'message', 'text' => 'Witaj '.$user_Name .' dziękujemy za Twoją Ofertę! Wkrótce się odezwiemy!.'));
    die($output);
}
}
?>

HTML和JS代码:

<script type="text/javascript">
$(document).ready(function() {
    $("#submit_btn").click(function() { 
        //get input field values

        var user_name       = $('input[name=name]').val(); 
        var user_email      = $('input[name=email]').val();
        var user_phone      = $('input[name=phone]').val();
        var user_marka      = $('input[name=marka]').val();
        var user_model      = $('input[name=model]').val();
        var user_rocznik    = $('input[name=rocznik]').val();
        var user_cena      = $('input[name=cena]').val();
        var attach_file     = $('input[name=file_attach]')[0].files[0];
        var user_message    = $('textarea[name=message]').val();

        //simple validation at client's end
        //we simply change border color to red if empty field using .css()
        var proceed = true;
        if(user_name==""){ 
            $('input[name=name]').css('border-color','red'); 
            proceed = false;
        }
        if(user_email==""){ 
            $('input[name=email]').css('border-color','red'); 
            proceed = false;
        }
        if(user_phone=="") {    
            $('input[name=phone]').css('border-color','red'); 
            proceed = false;
        }
         if(user_marka=="") {    
            $('input[name=marka]').css('border-color','red'); 
            proceed = false;
        }
         if(user_model=="") {    
            $('input[name=model]').css('border-color','red'); 
            proceed = false;
        }
         if(user_rocznik=="") {    
            $('input[name=rocznik]').css('border-color','red'); 
            proceed = false;
        }
         if(user_cena=="") {    
            $('input[name=cena]').css('border-color','red'); 
            proceed = false;
        }
        if(user_message=="") {  
            $('textarea[name=message]').css('border-color','red'); 
            proceed = false;
        }

        //everything looks good! proceed...
        if(proceed) 
        {
            $(".loading-img").show(); //show loading image
            $(".submit_btn").hide(); //hide submit button

            //data to be sent to server         
            var post_data = new FormData();    
            post_data.append( 'userName', user_name );
            post_data.append( 'userEmail', user_email );
            post_data.append( 'userPhone', user_phone );
            post_data.append( 'userMarka', user_marka );
            post_data.append( 'userModel', user_model );
            post_data.append( 'userRocznik', user_rocznik );
            post_data.append( 'userCena', user_cena );
            post_data.append( 'userMessage',user_message);
            post_data.append( 'file_attach', attach_file );

            //instead of $.post() we are using $.ajax()
            //that's because $.ajax() has more options and can be used more flexibly.
            $.ajax({
              url: 'contactus.php',
              data: post_data,
              processData: false,
              contentType: false,
              type: 'POST',
              dataType:'json',
              success: function(data){
                    //load json data from server and output message     
                    if(data.type == 'error')
                    {
                        output = '<div class="error">'+data.text+'</div>';
                    }else{
                        output = '<div class="success">'+data.text+'</div>';

                        //reset values in all input fields
                        $('#contact_form input').val(''); 
                        $('#contact_form textarea').val(''); 
                    }

                    $("#result").hide().html(output).slideDown(); //show results from server
                    $(".loading-img").hide(); //hide loading image
                    $(".submit_btn").show(); //show submit button
              }
            });

        }
    });

    //reset previously set border colors and hide all message on .keyup()
    $("#contact_form input, #contact_form textarea").keyup(function() { 
        $("#contact_form input, #contact_form textarea").css('border-color',''); 
        $("#result").slideUp();
    });

});
</script>


<label for="attach"><span>Zdjęcia Pojazdu: </span>
<input type="file" name="file_attach" id="file_attach"  multiple="multiple" />

2 个答案:

答案 0 :(得分:0)

也许你帮忙创造 $ encoded_content,$ file_type和$ file_name作为数组。

结束此atachment文件的数组中的每个值,并且您可以为每个元素写入新标题

foreach($encoded_content as $key => $content) {
    $headers .= "Content-Type:  ".$file_type[$key]."  ";
    $headers .= "name = ".$file_name[$key]."\r\n";
    $headers .= "Content-Disposition: attachment\r\n";
    $headers .= "Content-Transfer-Encoding: base64\r\n\r\n";
    $headers .= $content."\r\n";
}

答案 1 :(得分:-1)

现在我的代码看起来像它,但它不起作用

if($file_attached) //continue if we have the file
{

    # Mail headers should work with most clients (including thunderbird)
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion()."\r\n";
    $headers .= "From:".$from_Email."\r\n";
    $headers .= "Subject:".$subject."\r\n";
    $headers .= "Reply-To: ".$user_Email."" . "\r\n";
    $headers .= "Content-Type: multipart/mixed; boundary=".md5('boundary1')."\r\n\r\n";

    $headers .= "--".md5('boundary1')."\r\n";
    $headers .= "Content-Type: multipart/alternative;  boundary=".md5('boundary2')."\r\n\r\n";

    $headers .= "--".md5('boundary2')."\r\n";
    $headers .= "Content-Type: text/plain; charset=utf-8\r\n\r\n";
    $headers .= $mail_body."\r\n\r\n";

    $headers .= "--".md5('boundary2')."--\r\n";

    $headers .= "--".md5('boundary1')."\r\n";

    foreach($encoded_content as $key => $content) {
    $headers .= "Content-Type:  ".$file_type[$key]."  ";
    $headers .= "name = ".$file_name[$key]."\r\n";
    $headers .= "Content-Disposition: attachment\r\n";
    $headers .= "Content-Transfer-Encoding: base64\r\n\r\n";
    $headers .= $content."\r\n";
}

    $headers .= $encoded_content."\r\n";
    $headers .= "--".md5('boundary1')."--"; 

}else{
    # Mail headers for plain text mail
    $headers = 'From: '.$from_Email.'' . "\r\n" .
    'Reply-To: '.$user_Email.'' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
}