mkdir():PhpWord 和 Laravel 10 中没有这样的文件或目录错误

问题描述 投票:0回答:1

我尝试使用 PhpWord 1.0 对象 Writer 在 Laravel 10 的存储文件夹中保存 Word 文档,但收到异常“mkdir():没有这样的文件或目录”。逻辑如下:

 // Set MS Word compatibility to MS Office 2007
        $phpWord->getCompatibility()->setOoxmlVersion(12);

        $filesBasePath = storage_path('app/references/');

        $referenceDir = session()->get('random_files_dir');

        if (!empty($referenceDir) and is_dir($filesBasePath . $referenceDir)) {

            $absoluteRefPath = $filesBasePath . $referenSceDir;
            // Saving the document as OOXML file.
            $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
            $objWriter->save($absoluteRefpath . '/references.docx');
        } else {
            $referenceDir = Str::random(8);
            $absoluteRefPath = $filesBasePath . $referenceDir;

            if (!File::isDirectory($absoluteRefPath)) {
                if (File::makeDirectory($absoluteRefPath, 0755, true, true)) {
                    // Saving the document as OOXML file.
                    $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
                    $objWriter->save($absoluteRefPath . '/references.docx');

                    session(['random_files_dir' => $referenceDir]);
                }
            }
        }

        return response()->download($absoluteRefPath . '/references.docx')

可能是什么问题?我在 centos 7 上运行

我希望将Word文档保存在storage/app/references/random文件夹中。正在创建随机文件夹,但 Phpword 对象编写器抛出异常。下面的行是抛出错误的行;

$objWriter->save(storage_path('references.docx'));
php linux laravel centos7 phpword
1个回答
0
投票

您的文件系统似乎遇到了困难。首先考虑使处理更简单。这不应该解决您的问题,因为 mkdir() 仍然在这条路径上被调用,但谁知道呢:

// Set MS Word compatibility to MS Office 2007
$phpWord->getCompatibility()->setOoxmlVersion(12);

$filesBasePath = storage_path('app/references/');

$referenceDir = session()->get('random_files_dir');
if (empty($referenceDir)) {
    $referenceDir = Str::random(8);
    session(['random_files_dir' => $referenceDir]);
}

$absoluteRefPath = $filesBasePath . $referenceDir;
File::ensureDirectoryExists($absoluteRefPath, 0755, true, true);

// Saving the document as OOXML file.
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save($absoluteRefPath . '/references.docx');

return response()->download($absoluteRefPath . '/references.docx')

现在,如果我没有弄错你的代码,导致问题的部分只是为文件创建临时目录以临时保存下载。

如果是这样,那就完全没有必要了。它可能有点便宜,因为这就是您在问题中担心的问题,但是如果您可以直接输出 docx 文件,而不首先在文件系统上进行往返:

// Set MS Word compatibility to MS Office 2007
$phpWord->getCompatibility()->setOoxmlVersion(12);
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');

return response()->streamDownload(function () use ($objWriter) {    
    $objWriter->save('php://output');
}, 'references.docx')

这将代码减少到五行,并且不再需要 mkdir() 调用,也不需要会话。 YMMV.

© www.soinside.com 2019 - 2024. All rights reserved.