Search code examples
phpjqueryfile-uploadblueimp

jQuery File Upload generating weird $_FILES array


Possible Duplicate:
Weird format of $_FILES array when having multiple fields

I'm using jQuery File Upload to upload files to my server.

Here's my handler:

$('#fileupload').fileupload({
    url: 'api/combox_upload.php',
    dataType: 'json',
    done: function (e, data) {
        console.log(data);
        $.each(data.result.files, function (index, file) {
            console.log(file);
            $('<p/>').text(file.name[0]).appendTo($file_uploads);
        });
    }
});

Which runs this file:

<?php
header('Content-type: application/json');
echo json_encode($_FILES);

But the $_FILES array I get back looks like this:

{"files":{"name":["Screenshot from 2012-12-10 11:41:35.png"],"type":["image\/png"],"tmp_name":["\/var\/tmp\/phpHfnnt2"],"error":[0],"size":[180546]}}

i.e., files is an object rather than array of files, and each property (name, type, etc.) is an array rather than a string.

I think they're "parallel arrays", i.e., if there were 2 files uploaded, there would be 2 entries in each.

But this isn't how the usual PHP $_FILES array looks. Is jQuery File Upload messing with it? Is there a way to get back the normal structure?

Their little example,

        $.each(data.result.files, function (index, file) {
            $('<p/>').text(file.name).appendTo(document.body);
        });

Suggests it should be in the format I'd expect (files being an array).


Solution

  • As per this answer, this seems to be expected behaviour.

    We can convert it back into the expected format via this little function I wrote:

    function array_zip_keys($map) {
        $result = array();
        foreach($map as $key=>$arr) {
            foreach(array_values($arr) as $i=>$el) {
                $result[$i][$key] = $el;
            }
        }
        return $result;
    }
    

    Usage:

    $files = array_zip_keys($_FILES['files']);