【问题标题】:php force download shows garbage on screenphp强制下载在屏幕上显示垃圾
【发布时间】:2012-01-21 00:03:39
【问题描述】:

我正在尝试从 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);
        }

    `    

【问题讨论】:

标签: php zip force-download


【解决方案1】:

好吧,给任何浏览器一个 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);
    }

【讨论】:

  • 在流式传输文件之前是否向浏览器回显任何内容(例如空格)?
  • @MarkBaker 你的评论应该是答案。
【解决方案2】:

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

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

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

此外,当强制下载时,请始终使用application/octet-stream,这将确保正确发送二进制文件。

【讨论】:

    猜你喜欢
    • 2012-04-16
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    相关资源
    最近更新 更多