使用PHP在页面上显示多个上传的图像

时间:2014-05-02 00:09:15

标签: php

好的,这是我到目前为止所得到的,我能够上传一个图像并将其显示在div中,但我似乎无法弄清楚如何加载多个图像。如在上传多个图像并在屏幕上显示所有上传的图像。感谢任何帮助,提前谢谢。

另外:我认为我必须为

设置一个变量

$ _ FILES [ '图像'] [ '名称'] [0] $ _FILES [ '图像'] [ '名称'] [1] 等

并做一个forloop打印出来?如果我错了,请纠正我?

<?php
// prevent timezone warnings
date_default_timezone_set('America/New_York');

// set the upload location
$UPLOADDIR = "tmp";

// if the form has been submitted then save and display the image(s)
if(isset($_POST['Submit'])){
    // loop through the uploaded files
    foreach ($_FILES as $key => $value){
        $image_tmp = $value['tmp_name'];
        $image = $value['name'];
        $image_file = "{$UPLOADDIR}{$image}";

        // move the file to the permanent location
        if(move_uploaded_file($image_tmp,$image_file)){
            echo <<<HEREDOC

<div style="float:left;margin-right:10px">
    <img src="{$image_file}" alt="file not found" /></br>
</div>

HEREDOC;
        }
        else{
            echo "<h1>image file upload failed, image too big after compression</h1>";
        }
    }
}
else{
    ?>

<form name='newad' method='post' enctype='multipart/form-data' action=''>
    <table>
    <tr>
        <td><input type='file' name='image'></td>
    </tr>
    <tr>
        <td><input name='Submit' type='submit' value='Upload image'></td>
    </tr>
</table>
</form>

<?php
}
?>

2 个答案:

答案 0 :(得分:0)

我&#39;我不确定这是哪个CMS / Framework,但如果你改变这一行

发件人

<input type='file' name='image'>

<input type='file' name='image[]' multiple>

希望这可以帮助你。

答案 1 :(得分:0)

多个文件怎么样,你必须有两个循环。将foreach放入for。 我相信这就是你想要的。确保tmp文件夹具有写入权限。

<?php
// prevent timezone warnings
date_default_timezone_set('America/New_York');

// set the upload location
$UPLOADDIR = "tmp";

// if the form has been submitted then save and display the image(s)
if(isset($_POST['Submit'])){

    $num_files = count($_FILES['image']['tmp_name']);

    for($x = 0; $x < $num_files; $x++){
        $image = $_FILES['image']['name'][$x];
        $image_file = $UPLOADDIR."/". $image;
        if(!is_uploaded_file($_FILES['image']['tmp_name'][$x])){
            $messages[] = '<h1>'.$image.' image file upload failed, image too big after compression</h1>."<br>"';
        }
        if (move_uploaded_file($_FILES["image"]["tmp_name"][$x],$image_file)){
            echo '
            <div style="float:left;margin-right:10px">
                <img src="'.$image_file.'" alt="file" /></br>
            </div>';
        } else{
            echo "<h1>image file upload failed, image too big after compression</h1>";
        }
    }
}else {
    ?>

<form name='newad' method='post' enctype='multipart/form-data' action=''>
    <table>
    <tr>
        <td><input type='file' name='image[]'></td>
    </tr>
    <tr>
        <td><input type='file' name='image[]'></td>
    </tr>
    <tr>
        <td><input name='Submit' type='submit' value='Upload image'></td>
    </tr>
</table>
</form>

<?php
}
?>