开发者

PHP - Upload multiple images

I need to upload multiple images via form. I thought that I will do it with no problem, but I have one.

When I try to do foreach and get image by image it is not acting like I hoped it will.

HTML

<form method="post" action="" enctype="multipart/form-data" id="frmImgUpload">
    <input name="fileImage[]" type="file" multiple="true" />
    <br />
    <input name="btnSubmit" type="submit" value="Upload" />
</form>

PHP

<?php
if ($_POST)
{
    echo "<pre>";
    foreach ($_FILES['fileImage'] as $file)
    {
        print_r($file);
        die(); // I want it to print first image content and then die to test this out...
        //imgUpload($file) - I already have working function that uploads one image
    }
}

What I expected from it to print out first image, instead it prints names of all the images.

Example

Array
(
    [0] => 002.jpg
    [1] => 003.jpg
    [2] => 004.jpg
    [3] => 005.jpg
)

What I want it to o开发者_高级运维utput

Array
(
    [name] => 002.jpg
    [type] => image/jpeg
    [tmp_name] => php68A5.tmp
    [error] => 0
    [size] => 359227
)

So how can I select image by image in the loop so I can upload them all?

Okey I found solution and this is how I did it, probably not the best way but it works.

foreach ($_FILES['fileImage']['name'] as $f)
{
    $file['name'] = $_FILES['fileImage']['name'][$i];
    $file['type'] = $_FILES['fileImage']['type'][$i];
    $file['tmp_name'] = $_FILES['fileImage']['tmp_name'][$i];
    $file['error'] = $_FILES['fileImage']['error'][$i];
    $file['size'] = $_FILES['fileImage']['size'][$i];
    imgUpload($file);
    $i++;
}


that array is formed in another way

it's something line this:

array ( 
    'name' => array (
       [0] => 'yourimagename',
       [1] => 'yourimagename2',
       ....
    ),
    'tmp_file' => array (
    ....

that shoud do it :

foreach ($_FILES['fileImage']['name'] as $file)
    {
        print_r($file);
        die(); // I want it to print first image content and then die to test this out...
        //imgUpload($file) - I already have working function that uploads one image
    }


You are basically asking of how to rebuild the $_FILES array to access subitems of them as one array.

$index = 0;
$field = 'fileImage';
$keys = array_keys($_FILES[$field]);
$file = array();
foreach($keys as $key)
{
    $file[$key] = $_FILES[$field][$key][$index];
}
print_r($file);

change $index to the value you need to pick a specific file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜