通过jQuery post发送类型文件的输入字段

时间:2017-01-16 22:01:25

标签: php jquery html file

我正在尝试更新发送带有短信的电子邮件的HTML表单,以允许使用php文件和jQuery验证脚本发送附件。

当绕过验证并直接在动作上设置php文件时,表单可以正常工作。当尝试应用现有的jQuery验证时,它无法发送文件并且没有执行php文件。对于文字输入字段$("#fieldname").val()效果很好,但对于文件类型,我尝试了.val()files[0].prop("files")[0],但都没有效果。

请在下面找到我用过的代码并提出建议(提前谢谢!):

HTML:

<form method="post" name="apply" id="apply" enctype="multipart/form-data" action="">
    <div class="form-group">
        <input type="text" class="form-control" placeholder="Name" name="name1" id="name1">
    </div>
    <div class="form-group">
        <input type="email" class="form-control" placeholder="Email" placeholder="Name" name="eml1" id="eml1">
    </div>
    <div class="form-group1">
        <div class="fileUpload btns">
            <img src="images/icons/upload.png" alt="image">
            <span>Attach your cv</span>
            <input type="file" class="upload" id="upld" name="upld" />
        </div>
        <button type="submit" class=" btn btn-orange">Submit now</button>
    </div>
</form>

的jQuery:

jQuery(document).ready(function($) {
    /*  FORM VALIDATION
    /*----------------------------------------------------*/
    /*-------Contact US-----*/
    $("#apply").validate({
        rules: {
            name1: {
                required: true
            },
            eml1: {
                required: true,
                email: true
            },
            upld: {
                required: true
            },
        },
        submitHandler: function(form) {
            var suburl = 'cvmail.php',
                cName = $("#name1").val(),
                cEml = $("#eml1").val(),
                cComment = $("#upld").files[0];
            $('#apply .form-message').show();
            var data = {
                'formid': 'apply',
                'cust_name': cName,
                'upld': cComment,
                'cust_email': cEml
            };
            $.post(suburl, data, function(response) {
                $('.apply-page-form').html(response);
                $('.apply-page-form').show();
                $('#apply').each(function() {
                    this.reset(); //CLEARS THE FORM AFTER SUBMISSION
                });
            });
            return false;
        }
    });
});

PHP:

<?php
if($_POST && isset($_FILES['upld']) {
    $name=$cust_name=$_POST['cust_name'];
    $email=$_POST['cust_email'];
    $email_to_send_to='info@mydomain.com';
    $cSub=$_POST['cSub'];
    $email_subject ="Candidate CV";
    $message = $_FILES['upld']['name']; //message  

    //Get uploaded file data
    $file_tmp_name    = $_FILES['upld']['tmp_name'];
    $file_name        = $_FILES['upld']['name'];
    $file_size        = $_FILES['upld']['size'];
    $file_type        = $_FILES['upld']['type'];
    $file_error       = $_FILES['upld']['error'];

    if($file_error > 0) {
        die('Upload error or No files uploaded');
    }
    //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));

    $boundary = md5("sanwebe");
    //header
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "From:".$name."\r\n";
    $headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";

    //plain text
    $body = "--$boundary\r\n";
    $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
    $body .= chunk_split(base64_encode($message));

    //attachment
    $body .= "--$boundary\r\n";
    $body .="Content-Type: $file_type; name=".$file_name."\r\n";
    $body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
    $body .="Content-Transfer-Encoding: base64\r\n";
    $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
    $body .= $encoded_content;

    $ret = @mail($email_to_send_to,$email_subject, $body, $headers);
    if($ret) {
        //output success or failure messages     
        die('Thank you for your email');
    } else {
        die('Could not send mail! Please check your PHP mail configuration.');  
    }
}

2 个答案:

答案 0 :(得分:0)

您必须使用表单数据来获取上传的文件。 在link

中有一个答案

答案 1 :(得分:0)

HTML:

  1. 更改&#34;名称&#34;的名称属性和&#34;电子邮件&#34;匹配你在php文件中所期望的那些。即:更改名称=&#34; name1&#34; to name =&#34; cust_name&#34;并为电子邮件做同样的事。
  2. <强>的Javascript

    1. 不要手动形成&#34;数据&#34;对象而不是使用此var data = new FormData($("#file_upload_form")[0]);
    2. 由于这不是一个简单的文字帖子,但包含一个文件,我建议您使用较长版本的ajax帖子,如下所示:
    3. &#13;
      &#13;
      $.ajax({
      	type: "POST",
      	url: suburl,
      	data: data,
      	contentType: false,
      	processData: false,
      	success: function(response) {
      		$('.apply-page-form').html(response);
      		$('.apply-page-form').show();
      		$('#apply').each(function() {
      			this.reset(); //CLEARS THE FORM AFTER SUBMISSION
      		});
      	}
      });
      &#13;
      &#13;
      &#13;

      1. 请注意ajax帖子设置contentType: false,processData: false,中的两个参数。通过ajax发送文件时,这些是必需的。
      2. <强> PHP

        1. 您的php在第一行有错误。你错过了一个结束括号&#34;)&#34;。
        2. &#34; cSub&#34;变量来自?它无处不在。此外,您似乎无法在任何地方使用它