每当我运行这个脚本,我得到一个损坏的文件。下载正在发生,但我得到一个损坏的文件。让它是一个zip文件,img文件,只有txt文件工作良好。请帮助
<?php
function download($file){
$file="1.jpg";
$dir = './files/';
$path = $dir.$file;
if(!file_exists($path)){
die('Error');
}else{
header('Content-Disposition: attachment; filename='.basename($path));
header('Content-Type: image/jpeg');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($path));
readfile($path);
}
}
download("1.jpg");
?>
变化
header('Content-Length: ' . filesize($file));
header('Content-Length: ' . filesize($path));
您正在设置Content-Length: 0
,因为您只传递文件名而不是将完整路径传递给filesize()
。结果,浏览器不下载任何字节就断开连接,你得到一个空文件。
你还应该删除这3行
ob_clean();
ob_start();
flush();
因为仅readfile()
就足以流式传输到浏览器。如果你给我们看了整个脚本
如果你想在php中强制下载一个文件,那么你可以使用:
重定向到你的文件的url:header("Location: $path");
这个方法非常常用,特别是当文件没有浏览器支持的MIME类型时。但是,如果您确实知道要下载的文件的MIME类型,那么强烈建议您为此使用适当的Content-type头。例如,如果你想强制下载一个jpg文件(在你的例子中),那么你将不得不使用这样的东西:
header('Content-Disposition: attachment; filename='.basename($path));
header('Content-Type: image/jpeg');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($path));
readfile($path);