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

Laravel使用File::copy报No such file or directory错误如何解决

问题原因

  • 路径拼接缺失目录分隔符:代码里$path.$fileName直接拼接时,$path末尾没有斜杠,最终生成的源文件路径和实际存储路径不一致。比如public_path('storage/documents/1')拼接test.jpg会变成/www/site/public/storage/documents/1test.jpg,和实际存储的/www/site/public/storage/documents/1/test.jpg不符,自然找不到文件。
  • 目标目录未提前创建:File::copy不会自动生成不存在的目录,如果storage/documents/download目录未创建、或目录权限不足,也会触发不存在类报错。

修复方案

调整文件处理部分的代码如下:

foreach($request->file('file') as $file)
{
    $path = public_path('storage/documents/'.$request->product_id);
    // 提前创建源目录,避免move时报错
    if (!\File::exists($path)) {
        \File::makeDirectory($path, 0755, true);
    }
    $fileName = time().'_'.$file->getClientOriginalName();
    $file->move($path, $fileName);

    $target = public_path('storage/documents/download');
    // 提前创建目标目录
    if (!\File::exists($target)) {
        \File::makeDirectory($target, 0755, true);
    }
    // 正确拼接路径,DIRECTORY_SEPARATOR会自动适配不同操作系统的目录分隔符
    $sourceFullPath = $path . DIRECTORY_SEPARATOR . $fileName;
    $targetFullPath = $target . DIRECTORY_SEPARATOR . $fileName;
    \File::copy($sourceFullPath, $targetFullPath);

    $fileData[] = $fileName;
}

其他实现同文件存两个目录的方案

  • 方案1:直接读取文件内容存两次,逻辑更简洁,不需要先move再copy
$fileContent = file_get_contents($file->getRealPath());
// 存入第一个目录
\Storage::disk('public')->put('documents/'.$request->product_id.'/'.$fileName, $fileContent);
// 存入第二个目录
\Storage::disk('public')->put('documents/download/'.$fileName, $fileContent);
  • 方案2:磁盘空间紧张的场景下,可以用软链接代替实际文件复制,占用空间极小
// 源文件路径和目标路径拼接正确的前提下,创建软链接
symlink($sourceFullPath, $targetFullPath);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:09:01