如何显示使用此PHP脚本上传的图像?

时间:2016-03-05 03:04:36

标签: php image

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

我只想获取此图片我上传到浏览器页面上显示!救命!我正确上传文件,所以我不像PHP那样担心HTML。

2 个答案:

答案 0 :(得分:0)

首先,您必须创建数据库和表。在表中,您应该提到文件将以varchar格式上载的路径(字段名称)。之后,当您移动文件( move_uploaded_file(....))时,您必须将路径插入数据库。那么你可以使用php轻松地从数据库中检索。

例如: -

    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {

      $sql_run=mysqli(**$YOUR_CONNECTION,"INSERT INTO yourTable(path) VALUE ('YOUR_PATH_NAME/FILE_NAME')**");
      if($sql_run)
      echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";

        } else {
            echo "Sorry, there was an error uploading your file.";
        }

然后是另一个phpfile

<?php
//SELECT query
?>
<img src="YOUR PATH/<?php echo $mysqli_fetch_assoc(....)?>">
?>

答案 1 :(得分:0)

<img src="<?php echo $target_file; ?>" />

这就是我使用过的,而且效果很好!