How to make file upload work with jQuery and xhr2 (empty $_FILES returned)

耗尽温柔 提交于 2019-12-21 21:24:03

问题


I am using the $.ajax method and xhr2 to upload a file using the $.ajax method.

When I assing any standard object to the $.ajax parameter data, a proper non empty array is returned in $_POST (php).

JS:

data : {name:"john doe"}

PHP: print_r($_POST)

Array
(
    [name] => john doe
)

However, when I assing a formData object to the parameter data in order to upload a file, an empty array is returned in $_FILES (php)

JS:

data : new FormData(document.getElementById('fileupload'))

PHP: print_r($_FILES)

Array
(
)

My html code is:

<form enctype="multipart/form-data">
<div id="myform">
    <input type="file" name="fileupload" id="fileupload" />

    <div id="submit">UPLOAD</div>
</div>
</form>

My jQuery code is:

$('#submit').click(function(){

    var formData = new FormData(document.getElementById('fileupload'));

    $.ajax({
           url : "upload.php",
           type: "POST",
           data : formData,
           xhr: function(){
                myXhr = $.ajaxSettings.xhr();
                return myXhr;
            },
           success: function(data, textStatus, jqXHR){
                console.log(data);
            },
           cache: false,
           contentType : false,
           processData: false
        });
});

Would you happen to know what is wrong with my code? I can't figure out why the file is not being uploaded. Thanks for your help.


回答1:


var element = document.getElementById("fileupload");
        var myfiles= element.files;
        var data = new FormData();
        var i=0;
        for (i = 0; i < myfiles.length; i++) {
                                data.append('file' + i, myfiles[i]);
                            }

                     $.ajax({
                            url: 'load.php', 
                            type: 'POST',
                            contentType: false, 
                            data: data, 
                            processData: false, 
                            cache: false
                        }).done(function(msg) {
                           //do something
                        });

Source Code: http://sw.solfin.net.co/index.php/programacion/php-y-jquery



来源:https://stackoverflow.com/questions/24089247/how-to-make-file-upload-work-with-jquery-and-xhr2-empty-files-returned

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!