如何使用AJAX和jQuery传递文件数据? [英] How to pass file data with AJAX and jQuery?

查看:86
本文介绍了如何使用AJAX和jQuery传递文件数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个允许用户填写数据的表单,如果选中了一个选项,则div会打开,用户可以选择上传文件及其提交。

I'm trying to create a form that allows a user to fill out data and if an option is checked a div opens up and the user has the option to upload a file along with their submission.

我遇到的问题是让文件通过ajax正确传递。我无法正确地将它整合在一起以获得我正在寻找的结果,这是我的PHP脚本的文件发布。这是我传递数据的代码:

The issue I am having is getting the file to pass thru ajax correct. I can't quite mesh it together properly to get the results that I am looking for which is the file posting to my php script. Here's my code for passing the data:

$(document).ready(function() {
$("#submit_btn").click(function() { 

    var proceed = true;
    //simple validation at client's end
    //loop through each field and we simply change border color to red for invalid fields       
    $("#contact_form input[required=true], #contact_form textarea[required=true]").each(function(){
        $(this).css('border-color',''); 
        if(!$.trim($(this).val())){ //if this field is empty 
            $(this).css('border-color','red'); //change border color to red   
            proceed = false; //set do not proceed flag
        }
        //check invalid email
        var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; 
        if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
            $(this).css('border-color','red'); //change border color to red   
            proceed = false; //set do not proceed flag              
        }   
    });

    if(proceed) //everything looks good! proceed...
    {
        //get input field values data to be sent to server

        var search_array = $('input[name="donation"]').map(function(){
                return $(this).val();
        }).get();

        post_data = {
            'user_name'     : $('input[name=full_name]').val(), 
            'user_email'    : $('input[name=email]').val(), 
            'address'   : $('input[name=address]').val(), 
            'address2'  : $('input[name=address2]').val(), 
            'city'  : $('input[name=city]').val(), 
            'state' : $('input[name=state]').val(), 
            'zip'   : $('input[name=zip]').val(), 
            'ccnum' : $('input[name=ccnum]').val(), 
            'expmonth'  : $('select[name=expmonth]').val(), 
            'expyear'   : $('select[name=expyear]').val(), 
            'cardname'  : $('input[name=cardname]').val(),
            'ccvcode'   : $('input[name=ccvcode]').val(),
            'donation'  : $('input[name=donation]:checked').val(),
            'donation_other'    : $('input[name=donation_other]').val(),
            'contact_phone' : $('input[name=contact_phone]').val(),
            'attached_file' : $('input[name=attached_file]').val(),
            'donatecomments'    : $('textarea[name=donatecomments]').val()
        };





        //Ajax post data to server
        $.post('https://www.xxxxxx.org/catch.php', post_data, function(response){  
            if(response.type == 'error'){ //load json data from server and output message     
                output = '<div class="error">'+response.text+'</div>';
            }else{


                output = '<div class="success">'+response.text+'</div>';
                //reset values in all input fields
                $("#contact_form  input[required=true], #contact_form textarea[required=true]").val(''); 
                $("#contact_form #contact_body").slideUp(); //hide form after success
                window.top.location.href = "https://www.xxxxxxxxx.org/thank-you";
            }
            $("#contact_form #contact_results").hide().html(output).slideDown();
        }, 'json');
    }
});

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

我的文件选择行:

<input id="attached_file" name="attached_file" style="width:220px;" placeholder="Enter an amount - No $ sign" type="file" value="" onfocus="jQuery(this).prev(&quot;input&quot;).attr(&quot;checked&quot;, true); if(jQuery(this).val() == &quot;Other&quot;) { jQuery(this).val(&quot;&quot;); }" onblur="if(jQuery(this).val().replace(&quot; &quot;, &quot;&quot;) == &quot;&quot;) { jQuery(this).val(&quot;Other&quot;); }" tabindex="18">

我如何才能获得实际文件数据?

How can I get the actual file data to pass as well?

推荐答案

您需要将文件存储为FormData。您仍然可以通过将表单数据附加到FormData对象来发送表单数据以及文件附件。请参阅下面的示例:

You'll need to store the file as FormData. You can still send the form data along with your file attachment by append your form data to the FormData object See below example:

注意:这例如假设它是一个xml文件。如果它不是xml文件,请不要使用xml部分(if语句中的最后3行)。

NOTE: This example is assuming it's an xml file. If it's not an xml file, don't use the xml portion (last 3 lines in the if statement).

JavaScript

// #fileUpload is to a input element of the type file
var file = $('#fileUpload')[0].files[0]
var fd = new FormData();
fd.append('theFile', file);
$.ajax({
    url: '...',
    type: 'POST',
    processData: false,
    contentType: false,
    data: fd,
    success: function (data, status, jqxhr) {
        //success code
    },
    error: function (jqxhr, status, msg) {
        //error code
    }
});

C#

protected void Page_Load(object sender, EventArgs e)
{        
    try
    {
        foreach (string file in Request.Files)
        {
            var fileContent = Request.Files[file];
            if (fileContent != null && fileContent.ContentLength > 0)
            {
                Stream stream = fileContent.InputStream;
                BinaryReader br = new BinaryReader(stream);
                byte[] binaryData = br.ReadBytes(fileContent.ContentLength);
                string xml = System.Text.Encoding.Default.GetString(binaryData);
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(xml);
            }
        }
    }
    catch (Exception ex)
    {

    }
}

这篇关于如何使用AJAX和jQuery传递文件数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆