【问题标题】:PHPWord any way to not write file to disk when downloading filePHPWord在下载文件时以任何方式不将文件写入磁盘
【发布时间】:2019-05-17 09:59:36
【问题描述】:

我正在使用 PHPWord 来生成 Word 文档,我希望有人能在这方面提供帮助。它现在的设置方式是从浏览器向我的服务器发送一个 ajax 请求,请求构建 PHPWord 文档。该文档已构​​建,并使用以下代码存储在服务器上的文件中:

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$fileName = $picklistDetails['file_name'] . ".docx";
$filePath = '../users/' . $userId . "_word_" . $fileName;
$objWriter->save($filePath); 

为了允许用户下载文件,一旦 ajax 请求成功,我使用 window.location 将用户发送到一个页面,该页面将 word 文档与此文件放在一起(允许开始下载):

$fileName = $this->session->word_file_name;
$filePath = $this->session->word_file_path;

header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=" . $fileName);
header("Content-Transfer-Encoding: binary");    
readfile($filePath);

这一切都很好,唯一的问题是我真的希望在下载之前不必将文件保存到服务器。我一直在研究 PHPWord,根据这篇文章 (Auto download the file attachment using PHPWord) 讨论了如何将文件发送到 php 的输出流而不是将其写入磁盘,但是因为构建 word 文档是在 ajax 中完成的,然后是单独的页面用于下载它,我认为这行不通。我错了吗?

同样在这篇文章 (Save Generated File to database PHPWORD) 中描述了如何将其存储到数据库中,但服务器上仍然存在文件的中间步骤,我需要避免。

有什么办法可以修改

$objWriter->save($filePath); 

不将其写入磁盘而是将其保存到变量或其他东西?然后我也许可以将其存储在可以加密的数据库中。

任何帮助将不胜感激。我是一个初学者 php 程序员,非常感谢您提供详细的帮助。祝你有美好的一天。

【问题讨论】:

    标签: php phpword


    【解决方案1】:

    应该和$objWriter->save("php://output");一样简单:

    $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
    $fileName = $picklistDetails['file_name'] . ".docx";
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=" . $fileName);
    header("Content-Transfer-Encoding: binary");    
    $objWriter->save("php://output");
    

    完全跳过重定向。只需window.location 直接到上面的代码 ^ 并且文件应该在构建完成后下载。

    【讨论】:

    • 为什么需要使用 ajax?只需window.location 到 ^ 页面。
    • 感谢您的回复。是的,我认为唯一的方法是按照您上面的建议,将 ajax 只是 window.location 删除到带有 FrankerZ 建议的代码的页面,并实际在那里构建 PHPWord 文档,而不是事先使用 ajax。感谢您的回复。
    猜你喜欢
    • 1970-01-01
    • 2010-12-01
    • 2022-01-18
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多