服务器上有一个文件。该文件是一个 ZIP 文件。
该文件必须通过我的服务器下载到客户端。
我尝试使用readfile功能,但它没有下载文件,而是显示奇怪的符号......
我在这里上传了它:http://b-games.co.il/test/download/
这是代码:
$file = "2title3.gif";
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;
}
我也尝试使用这个:
$url = 'http://example.com/some.url';
$src = fopen($url, 'r');
$dest = fopen('php://output', 'w');
$bytesCopied = stream_copy_to_stream($src, $dest);
但它做了同样的事情...只是显示奇怪的符号。
我做错了什么?http://php.net/manual/en/function.readfile.php在这里它说它应该工作...
一个重要的更新:
在我的本地主机上,相同的代码有效!
有人知道为什么吗?
谢谢!
<?php
header('Content-disposition: attachment; filename=file.gif');
header('Content-type: image/gif');
readfile('file.gif');
您可以尝试这样的事情,请注意设置正确的内容类型。
这已经奏效了..
<?php
session_start();
$a=$_GET['a'];
$parts=explode("-",$a);
$tres=$parts[0];
$nombre=$partes[1];
$dbcodletra=substr($tres,2);
if($dbcod!=$_SESSION["username"])$boolt=0;
if($ext==1) $extl=".jpg";
if($ext==2) $extl=".jpeg";
if($ext==3) $extl=".tif";
if($ext==4) $extl=".tiff";
if($ext==5) $extl=".pdf";
if($ext==6) $extl=".doc";
if($ext==7) $extl=".docx";
if($tipoproy==1) $dir="rute/".$dbcodletra."/".$nombre.$extl;
if($tipoproy==2) $dir="rute/".$dbcodletra."/".$nombre.$extl;
if($tipoproy==3) $dir="rute/".$dbcodletra."/".$nombre.$extl;
if($tipoproy==4) $dir="rute/".$dbcodletra."/".$nombre.$extl;
if (file_exists($dir) && $boolt) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($dir));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($dir));
ob_clean();
flush();
readfile($dir);
exit;
}else echo "<meta http-equiv='"Refresh'" content='"0;url=misdocumentos.php'">";
?>
从php-image-file-download-by-code
这似乎是您的服务器上的问题。打开虚拟服务器上的PHP错误报告,并告诉我们它说了什么。目前,所有应该正常工作的东西都在工作。如果所有其他方法都失败了,可以尝试JavaScript。
这似乎是php-force-download-extension的重复。
"真正的"问题(恕我直言)是你已经生成了一个输出,并且你没有在代码的开头ob_start(),所以ob_clean()什么都不做。
编辑
这是您的PHP修改为仅下载GIF
<?php
ob_start();
// put some business here
$file = "2title3.gif";
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();
readfile($file);
exit;
}
编辑 2
我看你的示例代码,可能是我找到了你真正想做的事情。尝试查看此示例。
使用 HTTP,每个请求只能发送一个 mime 类型,因此您需要 2 个请求:一个用于 HTML(显示示例),一个用于下载(按提交按钮)。