dongyuan8024
dongyuan8024
2015-03-03 12:33

一个ajax中的数据和文件 - 如何处理JS FormData发出的帖子

已采纳

i`m struggling with one problem. I used example from this thread

Data and files in one ajax

I used this example

$("form#data").submit(function(){

var formData = new FormData($(this)[0]);

$.ajax({
    url: window.location.pathname,
    type: 'POST',
    data: formData,
    async: false,
    success: function (data) {
        alert(data)
    },
    cache: false,
    contentType: false,
    processData: false
});

return false; 

});

My example looks like this:

HTML Form + Ajax send

<form enctype="multipart/form-data" method="post" name="fileinfo" id="fm" action="">
    <label>Your email address:</label>
    <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br />
    <label>Custom file label:</label>
    <input type="text" name="filelabel" size="12" maxlength="32" /><br />
    <label>File to stash:</label>
    <input type="file" name="file" required />
    <input type="submit" value="Stash the file!" />
</form>
<div id="output"></div>



<script>
    $('#fm').on('submit', function (event) {

        event.preventDefault();

        var fd = new FormData($(this)[0]);
        fd.append("CustomField", "This is some extra data");
        $.ajax({
            url: __baseUrlWWW + "/test.php",
            type: "POST",
            data: fd,
            processData: false, // tell jQuery not to process the data
            contentType: false   // tell jQuery not to set contentType
        });

        return false;


    });

</script>

And everything would be ok - but when i`m sending this to php, i have problem with reading the post. I have POST in this form

Firebug return

Array
(
    [file] => Array
        (
            [name] => test.png
            [type] => image/png
            [tmp_name] => C:\wamp\tmp\php4E16.tmp
            [error] => 0
            [size] => 507
        )

)
Array
(
    [userid] => okok@dsada.eu
    [filelabel] => test
    [CustomField] => This is some extra data
)

HTML return in browser new tab

 Array (
[
-----------------------------318572418129603 Content-Disposition:_form - data;
_name] => "userid" okok@dsada.eu
-----------------------------318572418129603 Content-Disposition: form - data;
name = "filelabel" test
-----------------------------318572418129603 Content-Disposition: form - data;
name = "file";
filename = "b24_uam.png" Content-Type: image/png PNG IHDRHHÚőpPLTE˙˙˙UÂÓ~°IDAThíŐAV1Pß˙Ň7lOytŽşP Óü°đňúęľâzý~ŐV\˛O-e'NëC=x3,OdePú>ľ<qł-?× îX~ Wóôą|hÚžŘҢäę~ŚÎÄ_ĺ;5 şÜťk[>Ë:˝^50`ŃÉSKEÖű@ö3v;wK]"kÄ[ŻSÖRyűćŢóö?ÎRy{ÂÇ^lů,á˙ż'îŘň˝Ź-\[ÓĹ(EĺdĎâeWČRÝŽš6z\°6şlÍŘËŹĽ*lÖŕáeZŮR=ĆFÓ50,5É-¨yímŠĘMđ˝1ĺ°ÔeÍ=ÔČRufGŁ`ŠËĺböđŔ句PöđČňQň-üÄđ×\°$'CvÄ÷Aay*żcÁRŮŠOďÖÝÍm)KFÍć^ [ôżŤŢŕŔčä-uz0óÚojy$_ôtSKMâkDN)¸eŠIüů#jć˝-˘ˇT¤×׎íkźů}b;] => "CustomField" This is some extra data 
#-----------------------------318572418129603-- ) 

And my question is - how to read this in php? Browser in firebug shows in console correct formated arrays - $_post and $_files, but view in browser shows it in this way. Im running it on wamp localhost - but that shouldn be the problem i think?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • doudun1934 doudun1934 6年前

    And I think i found the answer - new tab is processing the post data so it cannot be displayed this way in new tab by clicking "open in new tab in firebug" on post request..

    I think i should give myself a vote down ;)

    点赞 评论 复制链接分享
  • dty5753 dty5753 6年前

    Your code updated

    <form enctype="multipart/form-data" method="post" name="fileinfo" id="fm" action="">
        <label>Your email address:</label>
        <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br />
        <label>Custom file label:</label>
        <input type="text" name="filelabel" size="12" maxlength="32" /><br />
        <label>File to stash:</label>
        <input type="file" name="file" required />
        <input type="submit" value="Stash the file!" />
    </form>
    <div id="output"></div>
    
    
    
    <script>
        $('#fm').on('submit', function (event) {
    
            event.preventDefault();
    
            var fd = new FormData($(this)[0]);
            fd.append("CustomField", "This is some extra data");
            $.ajax({
                url: __baseUrlWWW + "/test.php",
                type: "POST",
                data: fd,
                processData: true, // this is default so you can remove the line
                contentType: 'multipart/form-data'
            });
    
            return false;
    
    
        });
    
    </script>
    

    The issue is that you are not sending the correct contentType and you are not allowing the call to transform the data you are adding to the querystring. The form is not posting since you are returning false so you are not sending the contentType that you setup in the form for sending a file upload. Then you tell the ajax call not to send a contentType in the header. You need to tell the ajax call you want to send multipart/form-data in the header. Then processData: true which is default will merge the FormData object into your querystring.

    The only reason you are getting the other form data is because you are creating the FormData object using the form you are "submitting".

    点赞 评论 复制链接分享