首页 > 解决方案 > 如何从 laravel 5.6 中的路径创建文件实例

问题描述

我想知道是否有一种方法可以创建一个file类似的实例,当用户发送一个input file知道项目中的路径时创建的实例。

我有一个文件夹,backups然后用户可以选择他想要恢复的文件,我希望将它们从备份文件夹移动到用户正在恢复的模型的文件夹

我试过这个

$path = public_path('images/news/');
    foreach($news as $new) {
        foreach($new->images as $image) {
            $imagepath = public_path('images/backup/news/'.$image->image);
            if(file_exists($imagepath)) {

                $this->fileCtrl->copy($imagepath, $path.$new->id);
            }
        }
    }

$this->fileCtrl是一个使用实例Illuminate\Filesystem\Filesystem as File;

这会尝试移动文件,但不是创建一个包含 id 和文件的文件夹,而是创建一个具有 id 且没有扩展名的文件。

那么如何创建文件的实例,或者在其他情况下,如何防止它创建文件并使其创建文件夹?

标签: phplaravel

解决方案


您显然需要创建目录

if (!file_exists($imagepath)) {
    //if path doesn't exist create the path and copy
    mkdir($imagepath, 0777, true);
    $this->fileCtrl->copy($imagepath, $path.$new->id);
}else{
    //just copy file to path
    $this->fileCtrl->copy($imagepath, $path.$new->id);
}

推荐阅读