如何一次发布一个图像而不是整个文件夹?

时间:2017-04-11 00:13:54

标签: php forms image post file-upload

这是我的代码,现在所有图像都是在点击发布按钮时上传和显示的,我试图让他们在点击发布按钮后一次显示一个,我试过丢失在if语句之后继续声明但是会导致图像损坏。我尝试在输出后添加一个中断,但当然只显示初始图像,有什么建议吗?

<?php  
$folder = "images/";

if(isset($_POST['post'])){
    if (is_dir($folder)) 
    {
        if ($open = opendir($folder)) 
        {
            while (($file = readdir($open)) != false)
            {
                if ($file == '.' || $file == '..')continue;
                {
                    echo '<img src = "images/'.$file.'" width = "150" height = 150>';
                }
            }

            closedir($open);
        }
    }


    if (isset($_POST['upload'])) 
    {
        $file_name = $_FILES['file']['name'];
        $file_type = $_FILES['file']['type'];
        $file_size = $_FILES['file']['size'];
        $file_tem_loc = $_FILES['file']['tmp_name'];
        $file_store = "images/".$file_name;

        if (move_uploaded_file($file_tem_loc, $file_store)) 
        {
            echo "files successfully uploaded";
        }
    }

}

?>

<form action = "?" method = "POST" enctype = "multipart/form-data">

    <label>Uploading Files</label>
    <p><input type = "file" name = "file"/> </p>
    <p> <input type = "submit" name = "upload" value = "Upload Images"> </p>
    <p> <input type = "submit" name = "post" value = "Post"> </p>
</form>

1 个答案:

答案 0 :(得分:0)

请尝试以下代码,

<?php  
$folder = "images/";
if (isset($_POST['upload'])) 
{
    $file_name = $_FILES['file']['name'];
    $file_type = $_FILES['file']['type'];
    $file_size = $_FILES['file']['size'];
    $file_tem_loc = $_FILES['file']['tmp_name'];
    $file_store = "images/".date('YmdHis').'_'.$file_name;

    if (move_uploaded_file($file_tem_loc, $file_store)) 
    {
        echo "<h3>File successfully uploaded<br>Here is the image that you recently uploaded</h3>";
        echo '<img src = "'.$file_store.'" width = "150" height = 150>';
    }
}

echo "<h3>Here are the images that you uploaded so far</h3>";
if (is_dir($folder)) 
{
    if ($open = opendir($folder)) 
    {
        while (($file = readdir($open)) != false)
        {
            if ($file == '.' || $file == '..')continue;
            {
                echo '<img src = "images/'.$file.'" width = "150" height = 150>';
            }
        }
        closedir($open);
    }
} ?>

<form action="?" method="POST" enctype="multipart/form-data">
    <label>Uploading Files</label>
    <p><input type = "file" name = "file"/> </p>
    <p> <input type = "submit" name = "upload" value = "Upload Images"> </p>
    <!--<p> <input type = "submit" name = "post" value = "Post"> </p>-->
</form>

请注意,我已经通过在文件名后附加时间戳来重命名上传的文件名,以避免上传多个图像的可能性,在这种情况下,它将覆盖现有文件或不允许上传新文件