简体   繁体   English

ajax文件无法以php电子邮件格式上传文件

[英]ajax file cannot upload file in php email form

I have problem with the ajax file. 我的ajax文件有问题。 The ajax file does not work with the php form. ajax文件不适用于php表单。 when I run the code it displays an error file_get_content error, file name empty. 当我运行代码时,它显示错误file_get_content错误,文件名为空。

The php code is working properly. php代码正常运行。 but the ajax file cannot transfer the file field value. 但是ajax文件无法传输文件字段值。 So the file cannot attach with mail. 因此该文件无法与邮件一起附加。

it shows the error: file name empty 它显示错误:文件名为空

plz help me to pass the file field value through the ajax file. 请帮助我通过ajax文件传递文件字段值。

<div>
<form  method="post" enctype="multipart/form-data" name="form1" id="form1"     action="contactus.php" onsubmit="xmlhttpPost('contactus.php', 'form1', 'Myresult', ''); return false;">
Name:<input name="name1" type="text"   value="" />
Address:<input name="address1" type="text"  value="" /> 
Phone:<input name="phone1" type="text" value=""/>
Email: <input name="email1" type="text" value="" />
File:<input name="file" type="file" size="35" id="file" />
Links:<input name="links1" type="text" value="" />
Subject:<input name="subject1" type="text" value="" />
Location:<select name="location">
              <option value="" selected="selected">--Select--</option>
              <option>1</option>
              <option>2</option>
              <option>3</option>
              <option>4</option>
              <option>5</option>
            </select>

Comments:<textarea name="comment1"  ></textarea>
<input name="submit" id="submit" type="submit"/>   
<div id="Myresult"></div>
</form>
</div>

php form(contactus.php) php表格(contactus.php)

<?php
if(isset($_POST['submit']))
{

 $name=$_POST['name1'];
$address=$_POST['address1'];
$phone=$_POST['phone1'];
$email=$_POST['email1'];
$subject=$_POST['subject1'];
$location=$_POST['location'];
$comment=$_POST['comment1'];
$links=$_POST['links1'];

$to='mail@mail.com';

 $message .= "\nName: ".$name."\n\n";
 $message .= "Address: ".$address."\n\n";
 $message .= "Phone: ".$phone."\n\n";
 $message .= "Email: ".$email."\n\n";
  $message .= "Links: ".$links."\n\n";
  $message .= "Location: ".$location."\n\n";
  $message .= "Comments:\n\n ".$comment."\n";



$attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name'])));
    $filename = $_FILES['file']['name'];
    $filetype = $_FILES['file']['type'];        
    $boundary =md5(date('r', time())); 

$headers = "From: $name <$email>\r\nReply-To: $name <$email>";
$headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";


$message="This is a multi-part message in MIME format.

  --_1_$boundary
 Content-Type: multipart/alternative; boundary=\"_2_$boundary\"

 --_2_$boundary
 Content-Type: text/plain; charset=\"iso-8859-1\"
 Content-Transfer-Encoding: 7bit

 $message

 --_2_$boundary--
 --_1_$boundary
 Content-Type: $filetype; name=\"$filename\" 
 Content-Transfer-Encoding: base64 
 Content-Disposition: attachment 

 $attachment

 --_1_$boundary--";

 mail($to,$subject,$message,$headers);

 print 'Thanks, your message sent!';

 }

 ?>

ajax.js ajax.js

function xmlhttpPost(strURL,formname,responsediv,responsemsg) {

var xmlHttpReq = false;

var self = this;

// Xhr per Mozilla/Safari/Ie7

if (window.XMLHttpRequest) {

    self.xmlHttpReq = new XMLHttpRequest();

}

// per tutte le altre versioni di IE

else if (window.ActiveXObject) {

    self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");

}

self.xmlHttpReq.open('POST', strURL, true);

self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

self.xmlHttpReq.onreadystatechange = function() {

    if (self.xmlHttpReq.readyState == 4) {

        // Quando pronta, visualizzo la risposta del form

        updatepage(self.xmlHttpReq.responseText,responsediv);

    }

    else{

        // In attesa della risposta del form visualizzo il msg di attesa

        updatepage(responsemsg,responsediv);



    }

}

  self.xmlHttpReq.send(getquerystring(formname));

}



 function getquerystring(formname) {

 var form = document.forms[formname];

var qstr = "";



function GetElemValue(name, value) {

    qstr += (qstr.length > 0 ? "&" : "")

        + escape(name).replace(/\+/g, "%2B") + "="

        + escape(value ? value : "").replace(/\+/g, "%2B");

        //+ escape(value ? value : "").replace(/\n/g, "%0D");

}



var elemArray = form.elements;

for (var i = 0; i < elemArray.length; i++) {

    var element = elemArray[i];

    var elemType = element.type.toUpperCase();

    var elemName = element.name;

    if (elemName) {

        if (elemType == "TEXT"

                || elemType == "TEXTAREA"

                || elemType == "PASSWORD"

                || elemType == "BUTTON"

                || elemType == "RESET"

                || elemType == "SUBMIT"

                || elemType == "FILE"

                || elemType == "IMAGE"

                || elemType == "HIDDEN")

            GetElemValue(elemName, element.value);

        else if (elemType == "CHECKBOX" && element.checked)

            GetElemValue(elemName, 

                element.value ? element.value : "On");

        else if (elemType == "RADIO" && element.checked)

            GetElemValue(elemName, element.value);

        else if (elemType.indexOf("SELECT") != -1)

            for (var j = 0; j < element.options.length; j++) {

                var option = element.options[j];

                if (option.selected)

                    GetElemValue(elemName,

                        option.value ? option.value : option.text);

            }

    }

}

return qstr;

}

function updatepage(str,responsediv){


document.getElementById(responsediv).innerHTML = str;


}

problems: 问题:

1) Standard AJAX cannot upload files. 1)标准AJAX无法上传文件。 The usual workaround is to build a form in a hidden <iframe> and perform a standard POST upload there. 通常的解决方法是在隐藏的<iframe>构建表单,然后在其中执行标准的POST上传。

2) Your code simply ASSUMES an upload has been performed AND succeeded. 2)您的代码仅假定已执行成功上传。 This is, frankly, stupid. 坦率地说,这是愚蠢的。 NEVER assume success when dealing with users. 与用户打交道时永远不要假设成功。 Always prepare for the worst. 始终做好最坏的准备。 Your code, at minimum, should have something like this: 您的代码至少应具有以下内容:

if ($_FILES['fieldname']['error'] !== UPLOAD_ERR_OK) {
   die("File upload failed with error code " . $_FILES['fieldname']['error']);
}

if you'd had something like that, you'd have gotten (probably) error code #4 - no file uploaded, because uploads cannot be done via AJAX. 如果您有类似的问题,则可能会得到错误代码4(可能是错误代码)-没有文件上传,因为无法通过AJAX完成上传。 The error codes are defined here: http://www.php.net/manual/en/features.file-upload.errors.php 错误代码在此处定义: http : //www.php.net/manual/zh/features.file-upload.errors.php

3) You are building your own mime emails, which is not the easiest thing to get right. 3)您正在建立自己的哑剧电子邮件,这不是最容易解决的问题。 Why don't you try using Swiftmailer or PHPMailer? 为什么不尝试使用Swiftmailer或PHPMailer? Both make sending a MIME email, with html, embedded attachments, etc... almost trivial. 两者都使得发送带有html,嵌入式附件等的MIME电子邮件几乎是微不足道的。 Virtually all of your MIME-building code would be reduced to a SINGLE line in either library. 几乎所有的MIME-建筑规范将减少到在任一图书馆单行

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

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