HTML 5 multi file upload with PHP

2019-01-11 08:24发布

问题:

Here is the code I have, and I'm wondering what I'm doing wrong that it doesn't display the name.

<form action = "self.php" method="post" enctype="multipart/form-data">
<input type="file" name="imageURL[]" id="imageURL" multiple="" />
<input type="submit" value="submit" name="submit" />
</form>

And the processing info that isn't working:

foreach ($_FILES['imageURL'] as $files[]) { 
    echo $files['file'];
}

Edit:

When changing my foreach loop to:

foreach ($_FILES['imageURL'] as $file) { 
    echo $file['name'];
}

Still nothing prints out.

However, when I do something like this:

foreach ($_FILES['imageURL']['name'] as $filename) { 
    echo $filename;
}

The filename does print. I don't know what that implies though.



SOLVED UPDATE:

As linked to by John Conde, the array interlace structure is different when uploading multiple files than when uploading a single file. To use foreach, we must restructure the array.

$files=array();
$fdata=$_FILES['imageURL'];
if(is_array($fdata['name'])){
for($i=0;$i<count($fdata['name']);++$i){
        $files[]=array(
    'name'    =>$fdata['name'][$i],
    'type'  => $fdata['type'][$i],
    'tmp_name'=>$fdata['tmp_name'][$i],
    'error' => $fdata['error'][$i], 
    'size'  => $fdata['size'][$i]  
    );
    }
}else $files[]=$fdata;

NOW we can use foreach to loop:

foreach ($files as $file) { 
    echo $file['name'];
}

回答1:

Try

foreach ($_FILES['imageURL'] as $file) { 
    echo $file['name'];
}

UPDATE:

Google found this tutorial which may help you



回答2:

Instead of using for() and recounting the number of items in the array, you can use a more elegant foreach()

$files=array();
$fdata=$_FILES['file'];
if(is_array($fdata['name'])){
    foreach ($fdata['name'] as $i => $d) {
        $files[] = array(
        'name' => $d,
        'tmp_name' => $fdata['tmp_name'][$i]
        );
    }
}
else $files[]=$fdata;


回答3:

Maybe I'm wrong, but wouldn't setting multiple="" turn multiple uploads off? Just use multiple by itself, as shown in the HTML5 spec or, for XHTML compatibility, multiple="multiple":

<input type="file" name="imageURL[]" id="imageURL" multiple />