【问题标题】:Laravel File Copy: failed to open stream: No such file or directoryLaravel 文件复制:无法打开流:没有这样的文件或目录
【发布时间】:2021-09-13 03:08:59
【问题描述】:

我正在使用File::copy 将上传的文件从主文件夹复制到我的目标文件夹。但它一直说没有这样的文件或目录。

public function store(Request $request)
{        
    $data = $request->validate([
        'name' => 'required',
        'product_id' => 'required',
        'price' => 'required',
        'file' => 'required',
        'file.*' => 'mimes:jpeg,jpg,png,svg,gif,csv,xlsx,pdf,docx',
        'publish' => 'required',
    ]);

    $fileData = [];
    
    if($request->hasFile('file'))
    {
        foreach($request->file('file') as $file)
        {
            $path = public_path('storage/documents/'.$request->product_id);
            $fileName = time().'_'.$file->getClientOriginalName();
            $file->move($path, $fileName);

            $target = public_path('storage/documents/download');
            \File::copy($path.$fileName, $target.$fileName); // errors here

            $fileData[] = $fileName;
        }
        $data['file'] = json_encode($fileData);
    }

    $document = Document::create($data);

    return redirect()->route('product.index')->with('success','Document added successfully');
}

我该如何解决这个问题,或者有没有其他方法可以将相同的文件上传到 2 个文件夹?

【问题讨论】:

    标签: laravel file copy


    【解决方案1】:

    您可能需要在路径和文件名之间使用目录分隔符,如下所示:

    \File::copy($path.$fileName, $target.$fileName); // errors here
    \File::copy($path.'/'.$fileName, $target.'/'.$fileName); // errors corrected
    

    【讨论】:

    • 然后尝试转储您的路径以查看它们是否是预期的目录。
    • dd($path): "C:\wamp64\www\myprojectname\public\storage/documents/3"
    • 路径正确,区别只是反斜杠和正斜杠
    【解决方案2】:

    您必须调试您的代码。请按照以下步骤操作

    1. 尝试打印文件路径的值。如果您发现任何错误,请更改它。
    2. 在配置文件夹中打开session.php文件并查找storage_path
    3. 更改您的文件夹权限,但它说没有目录,所以可能是其他问题。
    4. 使用php artisan cache:clearphp artisan config:clear 清除您的配置或其他缓存

    【讨论】:

    • 我的配置中的storage_path'files' => storage_path('framework/sessions'),
    • 然后尝试清除缓存并打印存储路径的值来检查是否正确
    • 我将两个文件都存储在公共路径中,并且路径 die dump 是正确的。
    • dd($path): C:\wamp64\www\myprojectname\public\storage/documents/3
    • 看起来斜线是错误的。更改它们并尝试使用新的。
    【解决方案3】:

    $file->move($path, $fileName);

    您正在移动文件,请先检查它是否已移动到那里。

    $target = public_path('storage/documents/download'); \File::copy($path.$fileName, $target.$fileName); // 这里有错误

    您的错误似乎与您移动的文件是否在该目录中正确移动有关。如果命名正确应该可以解决

    \File::copy(base_path('test.text'),base_path('public/test.text'));
    

    检查名称并移动文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 2015-11-14
      • 2015-10-10
      • 2020-01-25
      • 2019-06-21
      • 2017-05-04
      相关资源
      最近更新 更多