簡體   English   中英

Laravel 將文件從一個磁盤移動到另一個磁盤 - 使用“存儲”

[英]Laravel move files from one disk to another disk - using `Storage`

我的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 facade 將文件從一個磁盤移動到另一個磁盤。 目前我需要它從一個本地磁盤工作到另一個本地磁盤,但將來我可能需要將它們從一個 S3 存儲桶移動到同一個存儲桶,從一個 S3 存儲桶移動到另一個存儲桶,或者從本地磁盤移動到 S3 存儲桶。

謝謝

如果您使用遠程路徑,我認為這種方式更干凈並且有效

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM