1

我使用此代码使用户能够下载 zip 文件:

if(file_exists($filename)){
         header("Content-Disposition: attachment; filename=".basename(str_replace(' ', '_', $filename)));
         header("Content-Type: application/force-download");
         header("Content-Type: application/octet-stream");
         header("Content-Type: application/download");
         header("Content-Description: File Transfer");
         header("Content-Length: " . filesize($filename));
         flush();

         $fp = fopen($filename, "r");
         while (!feof($fp))
         {
             echo fread($fp, 65536);
             flush();
         }
         fclose($fp);
     exit;
}

下载文件时,它仅下载 25,632 KB 的数据。但是 zip 文件是 26,252 KB...

为什么浏览器获得全部 25MB 但随后停止?

我检查了Content-Length标题以确保它是正确的并且它是......

编辑

在firefox中,当我下载文件时,它显示'of 25mb' 所以浏览器认为25mb是完整的数量......但是,echo'd时的内容长度是26252904?

4

5 回答 5

6

在你的代码之前添加这个

ob_clean();
ob_end_flush();
于 2016-03-12T09:55:03.010 回答
3

您的header('Content-Type ...)电话没有用,因为只有最后一个电话会发送到浏览器。

下载由 触发Content-Disposition: attachmentContent-Type: application/zip如果您要发送 zip 文件,则应发送实际文件。

最后,您的读取循环是不必要的。

综上所述,您的代码应如下所示:

if (file_exists($filename)) {
    $quoted_filename = basename(addcslashes($filename, "\0..\37\"\177"));
    header("Content-Disposition: attachment; filename=\"{$quoted_filename}\"");
    header('Content-Type: application/zip');
    header('Content-Length: '.filesize($filename));
    readfile($filename);
}
于 2012-05-30T13:53:45.870 回答
0

使用单个 MIME 类型来表示数据。

在这种情况下,使用application/octet-stream就可以了。这是您事先不知道 MIME 的时候。当你知道它,你必须把它。不要使用多个内容类型标头。

通常,当浏览器不知道如何处理特定的 MIME 时,它会触发下载过程。此外,使用Content-disposition: Attachment; ..确保它。

有一个简单readfile($filename)的方法会将文件的字节发送到请求进程,如下所示:

header("Content-disposition: attachment;filename=" . basename($filename);
readfile($filename);
于 2012-05-30T13:24:25.277 回答
0

我有类似的问题。该文件在 Firefox 中下载良好,但在 IE 中没有。似乎 Apache 正在压缩文件,而 IE 无法解压缩,因此文件已损坏。解决方案是在 Apache 中禁用 gzip。您还可以检查 PHP 是否没有即时压缩并禁用它。对于 Apache,您可以尝试:

SetEnv no-gzip 1

对于 PHP,在 .htaccess 中:

php_flag zlib.output_compression on
于 2012-05-30T14:07:45.007 回答
0

这个答案绝不是真正的答案。

但是我确实让它工作了......我只是将 Content-Length 设置为 30000000。因此它认为该文件比实际大小要大,然后它会全部下载。

我知道丑陋的黑客,但我找不到其他方法

于 2012-05-30T14:39:08.163 回答