PHP文件未下载-标头未提示下载

时间:2019-11-28 06:54:04

标签: php download header ziparchive response-headers

我遇到一个问题,尝试用zip文件读取文件时,试图提示浏览器打开保存对话框。我基本上已经用尽了我能找到的所有其他资源。我已经确认没有提前发送标头(没有错误,并且headers_sent()在测试中返回false),并且在Chrome / Firefox中检查响应时,我还可以看到正确的响应标头。该文件实质上以二进制形式返回,但不提示下载。使用PHP 7.2和Apache 2.4。任何帮助都会很棒,不知道我现在要去哪里。

    public function downloadFile() {
        $tmpfile = '/path/to/file.zip';
        header('Content-Type: octet-stream');
        header('Content-Description: File Transfer');
        header("Content-Length: " . filesize($tmpfile));
        header("Content-Transfer-Encoding: Binary"); 
        header('Content-Disposition: attachment; filename=' . basename($tmpfile));
        ob_clean();
        readfile($tmpfile);
        exit();
    }

这是通过GET请求进行请求的,如果我使用Postman和“发送并下载”功能,则可以保存文件,并且它是一个有效的zip,正如预期的那样,但是我无法获取浏览器下载。

编辑:我想添加八位字节流是错误的,但是将其更改为 application / octet-stream 之后,没有任何变化。我也尝试过 application / zip

这也是我得到的响应头:

HTTP/1.1 200 OK
Date: Thu, 28 Nov 2019 16:13:25 GMT
Server: Apache/2.4.39 (Win64) PHP/7.2.18
X-Powered-By: PHP/7.2.18
Content-Description: File Transfer
Content-Length: 386
Content-Transfer-Encoding: Binary
Content-Disposition: attachment; filename=filename.zip
Keep-Alive: timeout=5, max=97
Connection: Keep-Alive
Content-Type: application/octet-stream

编辑#2: 我也尝试添加以下内容,但没有成功。

header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');

2 个答案:

答案 0 :(得分:0)

您的哑剧类型缺少一部分: 应用程序/八位字节流

答案 1 :(得分:0)

尝试使用此标题:

header('Content-Type: application/octet-stream');

代替

header('Content-Type: octet-stream');

编辑: 这也可能是有效的(未试用):

header('Content-Type: application/zip');

编辑2: 添加使用readfile()时在此处提到的这些标头:

header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');

https://www.php.net/manual/en/function.readfile.php#refsect1-function.readfile-examples