php force download在屏幕上显示垃圾

时间:2011-12-15 09:11:44

标签: php zip force-download

我正在尝试从Ubuntu中的/ tmp文件夹下载一个zip文件。但是,当我运行Php代码时,它会在浏览器上显示垃圾文本,而不是显示下载框。我尝试使用一个简单的文本文件,而不是向我显示一个下载对话框,它将其内容打印在浏览器上。为什么这种强制下载不起作用。以下是代码。

if (file_exists($dir.$filename)) {
            header("Content-type: application/force-download");
            header("Content-Transfer-Encoding: Binary");
            header("Content-length: ".filesize($dir.$filename));
            header('Content-disposition: attachment; filename='.basename($dir.$filename));
            readfile($dir.$filename);
            exit(0);
        }

    `    

2 个答案:

答案 0 :(得分:4)

好吧,如果任何浏览器的MIME类型为“应用程序/强制下载”,浏览器将不知道如何处理它。

由于它是一个zip文件,因此MIME类型应为“application / octet-stream”或“application / zip”。

if (file_exists($dir . $filename)) {
        header("Content-type: application/zip");
        header("Content-Transfer-Encoding: Binary");
        header("Content-length: " . filesize($dir . $filename));
        header('Content-disposition: attachment; filename=' . basename($dir . $filename));
        readfile($dir . $filename);
        exit(0);
    }

答案 1 :(得分:0)

您无法将整个文件读入内存。更改你的readfile($ _ REQUEST ['file']);进入:

$handle=fopen($_REQUEST['file'], 'rb');
while (!feof($handle))
{
    echo fread($handle, 8192);
    flush();
}
fclose($handle);

这将读取8kb的文件,然后将其推送到客户端,依此类推......它将消耗不多的内存(因为它不会立即读取整个文件)。

同样,当强制下载总是使用application/octet-stream时,这将确保正确发送二进制文件。