Laravel使用`Storage`将文件从一个磁盘移动到另一磁盘

时间:2018-09-06 16:20:43

标签: amazon-s3 atomic laravel-5.6 laravel-filesystem

我的filesystems.php配置文件中定义了两个磁盘:

'd1' => [
    'driver' => 'local',
    'root' => storage_path('app/d1'),
],
'd2' => [
   'driver' => 'local',
   'root' => storage_path('app/d2'),
],

这些磁盘也可以是Amazon S3存储桶,并且可以是S3存储桶和本地磁盘的组合。

假设我有一个文件app/d1/myfile.txt,我想移至app/d2/myfile.txt

我现在正在做的是

$f = 'myfile.txt';
$file = Storage::disk('d1')->get($f);
Storage::disk('d2')->put($f, $file);

并将原始文件保留在d1上,因为它不会打扰我(我会定期从d1删除文件)。

我的问题是:

原子代码下的代码是什么,如何检查原子代码,如果不是,我如何使其原子化(对于文件为1GB或类似大小的情况):< / p>

$f = 'myfile.txt';
$file = Storage::disk('d1')->get($f);
Storage::disk('d2')->put($f, $file);
Storage::disk('d1')->delete($f);

是否存在是使用Storage门面将文件从一个磁盘移动到另一个磁盘的一种简单方法。目前,我需要它从一个本地磁盘移动到另一个本地磁盘,但是将来我可能需要将它们从一个S3存储桶移动到同一磁盘,从一个S3存储桶移动到另一个磁盘,或者从本地磁盘移动到S3存储桶。

谢谢

1 个答案:

答案 0 :(得分:0)

可以使用move方法将现有文件重命名或移动到新位置。

Storage::move('old/file.jpg', 'new/file.jpg');

但是,要在磁盘之间执行此操作,您需要具有要移动的文件的完整路径。

    // convert to full paths
    $pathSource = Storage::disk($sourceDisk)->getDriver()->getAdapter()->applyPathPrefix($sourceFile);
    $destinationPath = Storage::disk($destDisk)->getDriver()->getAdapter()->applyPathPrefix($destFile);

    // make destination folder
    if (!File::exists(dirname($destinationPath))) {
        File::makeDirectory(dirname($destinationPath), null, true);
    }

    File::move($pathSource, $destinationPath);
相关问题