0

所以我有一个表格来处理附件这是php代码

<?php

    //we need to get our variables first

    $email_to =   'xemax@tiscalinet.it'; //the address to which the email will be sent
    $name     =   $_POST['name'];  
    $email    =   $_POST['email'];
    $subject  =   "www.goliaerrante.com";
    $message  =   'Nome: '.$_POST['name'].chr(10) . chr(10) . 
                  'Email: '.$_POST['email'].chr(10) . chr(10) .
                  'Telefono: '.$_POST['subject'].chr(10) . chr(10) .
                  'Messaggio: '.$_POST['message'];


$allegato = $_FILES['allegato']['tmp_name'];
$allegato_type = $_FILES['allegato']['type'];
$allegato_name = $_FILES['allegato']['name'];


$msg = "";
$headers = "From: " . $email;


// Verifico se il file è stato caricato correttamente via HTTP
// In caso affermativo proseguo nel lavoro...
if (is_uploaded_file($allegato))
{
  // Apro e leggo il file allegato
  $file = fopen($allegato,'rb');
  $data = fread($file, filesize($allegato));
  fclose($file);

  // Adatto il file al formato MIME base64 usando base64_encode
  $data = chunk_split(base64_encode($data));

  // Genero il "separatore"
  // Serve per dividere, appunto, le varie parti del messaggio.
  // Nel nostro caso separerà la parte testuale dall'allegato
  $semi_rand = md5(time());
  $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

  // Aggiungo le intestazioni necessarie per l'allegato
  $headers .= "\nMIME-Version: 1.0\n";
  $headers .= "Content-Type: multipart/mixed;\n";
  $headers .= " boundary=\"{$mime_boundary}\"";

  // Definisco il tipo di messaggio (MIME/multi-part)
  $msg .= "This is a multi-part message in MIME format.\n\n";

  // Metto il separatore
  $msg .= "--{$mime_boundary}\n";

  // Questa è la parte "testuale" del messaggio
  $msg .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
  $msg .= "Content-Transfer-Encoding: 7bit\n\n";
  $msg .= $message . "\n\n";

  // Metto il separatore
  $msg .= "--{$mime_boundary}\n";

  // Aggiungo l'allegato al messaggio
  $msg .= "Content-Disposition: attachment;\n";
  $msg .= " filename=\"{$allegato_name}\"\n";
  $msg .= "Content-Transfer-Encoding: base64\n\n";
  $msg .= $data . "\n\n";

  // chiudo con il separatore
  $msg .= "--{$mime_boundary}--\n";
}
else
{
  $msg = $message;
}




// Invio la mail
if (mail($email_to,  $subject, $msg, $headers))
{
  echo 'sent'; // we are sending this text to the ajax request telling it that the mail is sent.. 
}else{
  echo 'failed';// ... or this one to tell it that it wasn't sent    
}
?>

现在我正在尝试调整这个 javascript 来处理消息结果;如果我不使用 javascript 一切正常,当我让 javascript 工作时,只发送电子邮件,没有附件..

$(document).ready(function(){  
    $('#send_message').click(function(e){  

        //stop the form from being submitted  
        e.preventDefault();  

        /* declare the variables, var error is the variable that we use on the end 
        to determine if there was an error or not */  
        var error = false;  
        var name = $('#name').val();  
        var email = $('#email').val();  
        var subject = $('#subject').val();  
        var message = $('#message').val();  

        /* in the next section we do the checking by using VARIABLE.length 
        where VARIABLE is the variable we are checking (like name, email), 
        length is a javascript function to get the number of characters. 
        And as you can see if the num of characters is 0 we set the error 
        variable to true and show the name_error div with the fadeIn effect. 
        if it's not 0 then we fadeOut the div( that's if the div is shown and 
        the error is fixed it fadesOut. 

        The only difference from these checks is the email checking, we have 
        email.indexOf('@') which checks if there is @ in the email input field. 
        This javascript function will return -1 if no occurence have been found.*/  
        if(name.length == 0){  
            var error = true;  
            $('#name_error').fadeIn(300);  
        }else{  
            $('#name_error').fadeOut(300);  
        }  
        if(email.length == 0 || email.indexOf('@') == '-1'){  
            var error = true;  
            $('#email_error').fadeIn(300);  
        }else{  
            $('#email_error').fadeOut(300);  
        }  
        if(subject.length == 0){  
            var error = true;  
            $('#subject_error').fadeIn(300);  
        }else{  
            $('#subject_error').fadeOut(300);  
        }  
        if(message.length == 0){  
            var error = true;  
            $('#message_error').fadeIn(300);  
        }else{  
            $('#message_error').fadeOut(300);  
        }  

        //now when the validation is done we check if the error variable is false (no errors)  
        if(error == false){  
            //disable the submit button to avoid spamming  
            //and change the button text to Sending...  
            $('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });  

            /* using the jquery's post(ajax) function and a lifesaver 
            function serialize() which gets all the data from the form 
            we submit it to send_email.php */  
            $.post("send_email.php", $("#contact_form").serialize(),function(result){  
                //and after the ajax request ends we check the text returned  
                if(result == 'sent'){ 
                    //if the mail is sent remove the submit paragraph 
                     $('#send_message').remove(); 
                    //and show the mail success div with fadeIn 
                    $('#mail_success').fadeIn(300); 
                }else{ 
                    //show the mail failed div 
                    $('#mail_fail').fadeIn(300); 
                    //reenable the submit button by removing attribute disabled and change the text back to Send The Message 
                    $('#send_message').removeAttr('disabled').attr('value', 'Send The Message');  
                }  
            });  
        }  
    });  
});
4

3 回答 3

1

前面有人提到,通过 XHR 上传文件所需的必要 HTML5 支持在 IE 中不存在,这在技术上是不正确的。IE10 支持您通过 XHR/ajax 上传文件所需的一切,将它们分割成分区并单独发送每个分区,稍后恢复失败或中断的上传等等。确实,对于不支持 HTML5 文件 API 的浏览器(例如 IE9 及更早版本,以及 Android 2.3.x 及更早版本),确实需要不同的解决方案。不要重新发明轮子,这只会给你带来头痛,而是使用已经存在的工具之一。我建议Fine Uploader无缝处理所有主流浏览器,具有许多功能,并且包括无依赖版本或 jQuery 版本。

有一些插件使用 Flash 或 Java 作为后备。这不是必需的,我建议您避免在客户端使用 Flash 和 Java,因为与客户端 Java 和 Flash 相关的严重安全问题以及这些会给您带来的支持噩梦。Flash 正在消亡,而 Java(客户端)已死。未来将不包括这两个选项中的任何一个,因此,为了您的用户群,请使用本机浏览器/javascript 方法。

于 2013-02-09T12:35:09.833 回答
1

you can't post files using jQuery.post because it may not be supported by some browsers XMLHttpRequest implementation (especially IE)

If you want to send files asynchronously (i.e AJAX) you have the following options:

  • Set the form's target to an iframe and submit it "to" the iframe and respond with some javascript that will invoke a javascript function in the parent document. Not really asynchronously, but it will keep you on the same page. No progress bar.

  • Using HTML5 (not supported by IE at the moment, but it should work with chrome, firefox, safari), google for "HTML5 File Upload" there are many articles like this one. Not supported by all browsers, a progress bar is possible.

  • If you want a cross-browser solution, have a look at plupload. Plupload tries to use HTML5 file uploads whenever possible, otherwise it will use a "hidden" flash uploader.

于 2013-02-09T12:06:40.287 回答
0

您不能使用纯 ajax 方法发送附件,文件不会发送。但是,有许多插件(黑客)可以异步处理它们(即:AjaxFileUpload)。

于 2013-02-09T12:02:59.717 回答