PHP 强制下载下载后无法打开文件


PHP force download can't open files after download

我正在尝试实现PHP强制下载并使用了下面的代码

$length = sprintf("%u", filesize($path));
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($path).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $length);
set_time_limit(0);
readfile($path);
exit;
文件

以全尺寸成功下载(我在记事本++中打开文件,没有php错误或警告(,但我无法打开文件。奇怪的是我可以毫无问题地下载和打开pdf文件。但是具有docx,png,jpg等格式的文件是一致的

尝试暂时删除内容长度标头,这可能是错误的,并导致文件下载不完整(可能只有一个字节(。还可以尝试将到期时间设置为高于 0;我已经看到IE中的错误是由此引起的,因为浏览器在外部程序有时间加载文件之前就从缓存中删除了该文件。

使用它进行强制下载

header("Cache-Control:  maxage=1");
header("Pragma: public");
header("Content-type: application/force-download");
header("Content-Transfer-Encoding: Binary");
header("Content-length: ".filesize($path));
header("Content-disposition: attachment; filename='"".basename($path)."'"");

我认为您应该使用正确的内容类型

以下是内容类型列表:http://www.freeformatter.com/mime-types-list.html

试试这段代码

$file = "xyz.html"
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
readfile($file);
    $file=FCPATH."downloaded/1462026746_IMG_2015.JPG"; //file location 
        if(file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit;
        }
        else {
            die('The provided file path is not valid.');
        }

ob_get_clean();> 在标题和 ob_clean(); flush(); readfile();之前

遇到了同样的问题,这为我解决了。