You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 10中使用PhpWord保存文档时出现mkdir()不存在目录错误

问题分析:PhpWord保存文档时抛出"mkdir(): No such file or directory"异常

问题背景

在CentOS 7环境的Laravel 10项目中,使用PhpWord 1.0的Object Writer将Word文档保存到storage目录时,抛出异常mkdir(): No such file or directory。期望文档保存至storage/app/references/下的随机文件夹(该文件夹已确认创建),但保存时出错,出错代码行如下:

$objWriter->save(storage_path('references.docx'));

完整代码

// 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')

问题排查点

  • 变量名拼写错误:
    • 第一个分支中,$absoluteRefPath = $filesBasePath . $referenSceDir; 里的$referenSceDir是拼写错误,正确变量名应为$referenceDir
    • 同分支下的$objWriter->save($absoluteRefpath . '/references.docx'); 中$absoluteRefpath存在大小写错误,PHP变量区分大小写,正确应为$absoluteRefPath
  • 目录权限问题:
    CentOS环境下需确保storage/app/references/及子目录的所有者为Web服务器运行用户(如apache、www-data),权限设置为755或775,避免因权限不足导致无法写入
  • 路径拼接不规范:
    手动拼接路径时的斜杠可能引发异常,建议使用系统目录分隔符规范路径:
    $filesBasePath = storage_path('app/references');
    $absoluteRefPath = $filesBasePath . DIRECTORY_SEPARATOR . $referenceDir;
    
  • PhpWord临时目录权限:
    PhpWord保存OOXML文档时需使用临时目录,若系统临时目录(如/tmp)权限不足,可手动指定Laravel内的临时目录:
    \PhpOffice\PhpWord\Settings::setTempDir(storage_path('app/temp'));
    
    需确保指定的临时目录已创建且权限正确

内容的提问来源于stack exchange,提问作者peter chege

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 08:35:31