PHP下载.jpg或.avi [英] PHP download .jpg or .avi

查看:122
本文介绍了PHP下载.jpg或.avi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,从服务器使用PHP
下载.jpg和.avi文件我有以下代码:

I have gotten a problem about downloading .jpg and .avi files from a server using PHP I have the following code:

$fileName = "Koala.jpg";
$filePath = "./Koala.jpg";
if (!file_exists($filePath)){
    echo "No file";
    return;
}
$fp = fopen($filePath, "r");
$fileSize = filesize($filePath);
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Content-Length: $fileSize");
header("Content-Disposition: attachment;filename=".$fileName);

$buffer = 1024;
while(!feof($fp)){
    $data = fread($fp, $fileSize);
    echo $data;
}
fclose($fp);

代码成功下载.txt文件,可以读取下载的文件。
但是,当涉及到.jpg时,下载的.jpg文件无法读取。
有人可以帮忙吗?感谢

The code downloads .txt file successfully and the downloaded file can be read. However, when it comes to .jpg, the downloaded .jpg file cannot be read. Can anyone give a helping hand? Thanks

刚刚尝试过另一种方法,它工作正常

Have just tried another method and it works fine

$file = 'Koala.jpg';

if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}

但只是想知道什么原因导致第一种方法失败,即使使用fopen xxx,rb)。谢谢

But just wonder what reason causes the first method fail, even though using fopen("xxx", "rb") instead. Thank you

推荐答案

而不是您使用的以下代码,

Instead of the following code that you are using,

$buffer = 1024;
while(!feof($fp)){
    $data = fread($fp, $fileSize);
    echo $data;
}

只需使用 readfile 方法

readfile($filePath);

这篇关于PHP下载.jpg或.avi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆