下载 docx 文件时出错

error downloading docx file

我正在生成 docx 并从服务器下载。

private static function downloadFile($fileDir)
{
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . basename($fileDir));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($fileDir));
    readfile($fileDir);
}

这是保存功能。如果我在服务器的临时目录中打开文件,它就可以工作。但是下载后,我有错误 "The file is damaged" 。我尝试恢复文件并恢复一切正常。错误在哪里?

readfile($fileDir) 之前,尝试 运行 ob_clean()flush() 清理(擦除)并刷新输出缓冲区。

引用自PHP's manual about flush()

flush() may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser. It also doesn't affect PHP's userspace output buffering mechanism. This means you will have to call both ob_flush() and flush() to flush the ob output buffers if you are using those.