【问题标题】:Failed to open files as files damaged when download from PHP从PHP下载时无法打开文件作为文件损坏
【发布时间】:2020-11-24 09:52:23
【问题描述】:

我在我的 Mac 机器上使用PHP 7.3.22,我正在尝试使用 PHP 函数下载文件。但我无法打开下载的文件,因为它们已损坏。我正在使用下面的代码下载

function downloadFile()
{
    $fileName = 'MyFile.zip';
    $fullPath = '/path/to/MyFile.zip';
    if(file_exists($fullPath)) {
        header('Content-Description: File Transfer');
        $contentType = mime_content_type($fullPath);
        header('Pragma: public');  // required
        header('Expires: 0');  // no cache
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Content-Type: '.$contentType);
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($fullPath)) . ' GMT');
        header('Content-disposition: attachment; filename=' . $fileName);
        header("Content-Transfer-Encoding:  binary");
        header('Content-Length: ' . filesize($fullPath)); // provide file size
        header('Connection: close');
        readfile($fullPath);
        exit();
    }
}

下载不受单一文件类型的限制。所以以编程方式获取内容类型

下载后打开zip文件时显示“Unadle to expand'MyFile.zip'. It is an unsupported format”

我在这里做错了吗?请帮助我完成这项工作。任何帮助都将不胜感激。

【问题讨论】:

    标签: php download php-7 php-7.3


    【解决方案1】:

    代码可以简化:

    $file_name = '/path/to/MyFile.zip';
    if(file_exists($file_name)) {
        header('Content-Type: application/octet-stream');
        header("Content-Transfer-Encoding: Binary"); 
        header("Content-disposition: attachment; filename=\"".$file_name."\""); 
        readfile($file_name);
        exit;
    }
    

    你必须确定PHP是否可以读取源文件;建议使用相对路径而不是绝对路径。

    【讨论】:

    • 谢谢。那是一个错字。解决了这个问题。即使内容类型正确,结果也一样
    • 知道了。许多标题条目可以省略。看看修改后的代码是否适合你。
    猜你喜欢
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 2015-07-16
    • 2021-04-07
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多