我有一个图像$file
(例如../image.jpg
)
,它具有mime类型$type
如何将其输出到浏览器?
发布于 2009-12-05 18:46:03
$file = '../image.jpg';
$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($file));
readfile($file);
发布于 2009-12-05 18:53:42
如果你可以自己配置你的网络服务器,像mod_xsendfile (用于Apache)这样的工具比用PHP读取和打印文件要好得多。您的PHP代码将如下所示:
header("Content-type: $type");
header("X-Sendfile: $file"); # make sure $file is the full path, not relative
exit();
mod_xsendfile拾取X-Sendfile头文件并将文件发送到浏览器本身。这可以在性能上产生真正的差异,特别是对于大文件。大多数建议的解决方案将整个文件读取到内存中,然后打印出来。这对于一个20kbyte的图像文件来说是可以的,但是如果你有一个200kbyte的MByte文件,你肯定会遇到问题。
发布于 2012-02-28 21:38:47
$file = '../image.jpg';
if (file_exists($file))
{
$size = getimagesize($file);
$fp = fopen($file, 'rb');
if ($size and $fp)
{
// Optional never cache
// header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
// header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
// header('Pragma: no-cache');
// Optional cache if not changed
// header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($file)).' GMT');
// Optional send not modified
// if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) and
// filemtime($file) == strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']))
// {
// header('HTTP/1.1 304 Not Modified');
// }
header('Content-Type: '.$size['mime']);
header('Content-Length: '.filesize($file));
fpassthru($fp);
exit;
}
}
https://stackoverflow.com/questions/1851849
复制相似问题