Question

I want to get a multiple files in an array with HTML5 form data object,

// HTML5 form data object.
var fd = new FormData();
jQuery.each(fileList, function (i, file) {
    fd.append('file[' + i + ']', file);
});

result,

Array
(
    [file] => Array
        (
            [name] => Array
                (
                    [0] => 1402236_566802636708984_1354256864_o.jpg
                    [1] => 287481_456592524374335_1348353782_o.jpg
                )

            [type] => Array
                (
                    [0] => image/jpeg
                    [1] => image/jpeg
                )

            [tmp_name] => Array
                (
                    [0] => C:\wamp\tmp\php5A1E.tmp
                    [1] => C:\wamp\tmp\php5A21.tmp
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                )

            [size] => Array
                (
                    [0] => 217360
                    [1] => 144071
                )

        )

)

but I am after this result,

Array
(
    [file] => Array
        (
            [0] => Array
                (
                    [name] => 1402236_566802636708984_1354256864_o.jpg
                    [type] => image/jpeg
                    [tmp_name] => C:\wamp\tmp\php35C1.tmp
                    [error] => 0
                    [size] => 217360
                )

            [1] => Array
                (
                    [name] => 964570_566803006708947_840223346_o.jpg
                    [type] => image/jpeg
                    [tmp_name] => C:\wamp\tmp\php35C4.tmp
                    [error] => 0
                    [size] => 518594
                )
        )

)

Is it possible?

Was it helpful?

Solution

This will get you started:

var newArr=[],
    keys= $.map(files.file,function( value, key){
        return key
    }),
        numFiles= files.file[keys[0]].length;

    for( i=0; i< numFiles; i++){
        var f={};
        $.each(keys, function( keyIdx, key){
           f[key]= files.file[key][i]; 
        });
        newArr.push(f);
    }

DEMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top