【问题标题】:Laravel move files from one disk to another disk - using `Storage`Laravel 将文件从一个磁盘移动到另一个磁盘 - 使用“存储”
【发布时间】:2019-02-11 23:22:55
【问题描述】:

我在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 或类似大小的场景):

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

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

谢谢

【问题讨论】:

  • 你用的是 laravel 5.6 吗?对于 5.7 有一个新功能Filesystem Read / Write Streams
  • 5.6 但升级应该不是问题。感谢您的提示,我会检查一下。
  • 转到页面底部,laravel.com/docs/5.7/releases

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


【解决方案1】:

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);

【讨论】:

  • 你也可以\File::ensureDirectoryExists($destinationPath);
【解决方案2】:

如果您使用远程路径,我认为这种方式更清洁并且有效

    $directories = ['dir1', 'dir2', 'dir3'];
    $from = 'public';
    $to = 'assets';

    foreach($directories as $directory){
        $files = Storage::disk($from)->allFiles($directory);

        foreach ($files as $file) {

            Storage::disk($to)->writeStream($file, Storage::disk($from)->readStream($file));

            // If you no longer need the originals
            //Storage::disk($from)->delete($file);
        }

        Storage::disk($from)->deleteDirectory($directory);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多