上传后显示图像

时间:2014-02-22 05:51:59

标签: php

这是我的uploadImage.php。我想在上传后立即显示图像。 问题是我不是什么问题。我试图改变它的一些,并来到这个代码。但仍然没有得到我预期的结果。有人在乎帮助我吗?

   <?php

   $tempFile = $_FILES["image"]["tmp_name"];
   $name = $_FILES["image"]["name"];
   $uploadDirectory = "/home/trainee/Desktop/tmp/";

   $allowedExts = array("gif", "jpeg", "jpg", "png");
   $temp = explode(".", $_FILES["file"]["name"]);
   $extension = end($temp);
   if ((($_FILES["image"]["type"] == "image/gif")
   || ($_FILES["image"]["type"] == "image/jpeg")
   || ($_FILES["image"]["type"] == "image/jpg")
   || ($_FILES["image"]["type"] == "image/pjpeg")
   || ($_FILES["image"]["type"] == "image/x-png")
   || ($_FILES["image"]["type"] == "image/png"))
   && ($_FILES["image"]["size"] < 20000)
   && in_array($extension, $allowedExts))
   {
     if ($_FILES["image"]["error"] > 0)
     {
       echo "Return Code: " . $_FILES["image"]["error"] . "<br>";
     }
     else
     {
       echo "Upload: " . $name. "<br>";
       echo "Type: " . $_FILES["image"]["type"] . "<br>";
       echo "Size: " . ($_FILES["image"]["size"] / 1024) . " kB<br>";
       echo "Temp file: " . $tempFile . "<br>";

       if (file_exists("$uploadDirectory" . $name))
       {
         echo $name . " already exists. ";
       }
       else
       {
     move_uploaded_file($tempFile, "$uploadDirectory/$name"),
     $name
         echo "Stored in: " ."$uploadDirectory". $name;
       }
    }
 }
 else {
 echo "invalid File!";
 }
 ?>
 <img src="upload/<?php=$name?>" height=200 width=100">

2 个答案:

答案 0 :(得分:0)

这是另一篇可能有帮助的帖子。 how to preview uploaded image in php form

据我所知,在上传之前,实际上无法预览图像。由于我们不希望页面重新加载或让用户在预览上传之前提交表单,因此我们需要使用ajax。

在提交表单之前,有很多ajax(javascript + php)选项和教程用于上传和预览图像。这是一个可能有用的教程。

答案 1 :(得分:0)

以下是代码的修复:

<?php
$tempFile = $_FILES["image"]["tmp_name"];
$name = $_FILES["image"]["name"];
$uploadDirectory = "/home/trainee/Desktop/tmp/";

$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$allowedFileTypes = array("image/gif", "image/jpeg", "image/jpg", "image/pjpeg",
        "image/x-png", "image/png");
if (in_array($_FILES["image"]["type"], $allowedFileTypes)
    && $_FILES["image"]["size"] < 20000
    && in_array($extension, $allowedExts))
{
  if ($_FILES["image"]["error"] > 0)
  {
    echo "Return Code: " . $_FILES["image"]["error"] . "<br>";
  }
  else
  {
    echo "Upload: " . $name. "<br>";
    echo "Type: " . $_FILES["image"]["type"] . "<br>";
    echo "Size: " . ($_FILES["image"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $tempFile . "<br>";

    if (file_exists($uploadDirectory . $name))
    {
      echo $name . " already exists. ";
    }
    else
    {
      move_uploaded_file($tempFile, $uploadDirectory . $name);
      echo "Stored in: " . $uploadDirectory . $name;
    }
  }
}
else
{
  echo "invalid File!";
}
?>
<img src="upload/<?php echo $uploadDirectory . $name; ?>" height="200" width="100">
  

注意: 您的上传目录必须可以从网络用户访问。目前似乎无法访问! :(