1

我有以下代码来推送 zip 文件以供下载。

$filename = "ResourcePack_".time().".zip";
        $destination = $basepath."downloads/$filename";
        if($this->createdownload($files,$destination,false)){
            header("Cache-Control: public");
            header("Content-Description: File Transfer");
            header("Content-Length: ". filesize("$destination").";");
            header("Content-Disposition: attachment; filename='$filename'");
            header("Content-Type: application/octet-stream; "); 
            header("Content-Transfer-Encoding: binary");
            ob_end_flush();
            @readfile($destination);

            if(file_exists($destination)){
                unlink($destination);
            }
        }

我知道 createdownload 函数可以很好地生成 zip 文件,因为我看到该文件正在服务器上创建。问题是文件被作为一堆垃圾写入浏览器,而不是打开下载流。我的标题中是否缺少某些内容?

编辑

我是对的。我的问题不在于 php,而是通过 JQuery $.ajax 调用调用生成此代码的 php 文件是问题所在。使用 $.ajax 会自动将 Accept-Encoding 请求标头设置为与 zip 文件不兼容的值。因此,除了使用 $.ajax 之外,我只使用了一个简单的 window.open javascript 命令来调用相同的 php 页面,并且它与标题一起工作得很好。

4

2 回答 2

0

尝试为该文件传递正确的类型。我认为它的 fileinfo mime 类型见http://www.php.net/manual/en/ref.fileinfo.php

header("Content-Type: $file_type");

在八位字节流删除它之后你也有分号

header("Content-type: application/octet-stream");
于 2012-06-29T17:35:36.127 回答
0

尝试在@readfile 之后放置一个骰子并删除@,以查看您是否有与文件读取相关的任何其他错误。

我有一些代码做同样的事情,这对我有用:

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private", false); // required for certain browsers
        header('Content-Disposition: inline; filename="' . $filename . '"');
        header('Content-type: application/zip');
        //header("Content-Transfer-Encoding: binary");
        header("Content-Length: " . filesize($destination));

        readfile($destination);
        die();
于 2012-06-29T17:49:52.247 回答