file_exist显示图像路径而不是.jpg


file_exist displaying image path instead of .jpg

我在这里用file_exist得到了一个代码。 它检查目录中是否存在.txt和.jpg文件。 然后在警报框中显示这些内容。 它适用于.txt,但在.jpg中则不行。 它显示图像源而不是图像本身。 我在这里做错了什么? 你能给我一些帮助吗? 提前非常感谢! 这是我的代码。

搜索.php

<?php
    class Model
    {
        public function readexisting()
        {
            if(
                file_exists($_SERVER['DOCUMENT_ROOT']."/Alchemy/events/folder-01/event-01.txt") 
                && 
                file_exists($_SERVER['DOCUMENT_ROOT']."/Alchemy/events/folder-01/event-01.jpg")
            )
            {  
                $myPic     =   "/Alchemy/ajax/events/folder-01/event-01.jpg";
                echo $myPic;
                $myFile    =   ($_SERVER['DOCUMENT_ROOT'] . "/Alchemy/events/folder-01/event-01.txt");
                $fh        =   fopen($myFile, 'r');
                $theData   =   fread($fh, filesize($myFile));
                fclose($fh);
                echo $theData ;
            }
            else
            {
                echo "The file $myFile does not exist";
            }
        }
    }
?>
您需要

应用header()并告诉PHP您正在渲染图像。

header("Content-type: image/jpeg");

或者,根据要渲染的文件,应用正确的标头。

删除echo $myPic;,然后将其添加到echo $theData;

header("Content-type: image/jpeg");

通常,您必须通知浏览器您要发送的数据类型。另请注意,header() 命令应在开始向浏览器发送任何数据之前找到。

此外,如果您要操作多种文件类型(即:png,jpg,gif),则应在deader命令中更改MIME类型以映射适当的文件类型。

header("Content-type: image/gif");   // For gif images
header("Content-type: image/png");   // For png images
header("Content-type: image/jpeg");   // For jpg images
<</div> div class="answers">

对于图像(或其他任何内容),您需要发送内容类型标头,否则将不会显示。您可以通过首先在此处获取 mime 类型,然后在 echo 之前执行此操作来添加标头来执行此操作。

header("Content-Type: ". $mimetype);
echo $theData;

其中$mimetype是检索的 MIME 类型。