How to make file upload work with jQuery and xhr2

2019-04-13 08:14发布

问题:

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