如何使用 flysystem 将文件从一个存储桶传输到另一个存储桶?

How can I transfer a file from one bucket to another using flysystem?

我有时需要将一个存储桶中的对象传输到 Amazon S3 中的第二个存储桶。我正在使用 Laravel 5.3 和 Flysystem 来管理这些存储桶。

一个解决方案是将图像下载到我的服务器,然后将其上传到另一个存储桶,但这似乎是一种浪费 time/bandwidth,因为该文件存在于 S3 中并且正在 S3 中移动。这可以在 Flysystem 中完成还是我需要直接使用亚马逊的 API?

您可以使用 FilesystemAdapter 移动功能移动文件:

$disk = Storage::disk('s3');
if (!$disk->move('bucketOne/testFile.jpg', 'bucketTwo/testFile.jpg')) {
   throw new \Exception('File could not be moved.');
}

我找到了解决办法。这是我的代码:

try {
    $s3 = Storage::disk('s3');
    $s3_temp = $s3->getDriver()->getAdapter()->getClient()->copy(
        env('S3_BUCKET_ORIGIN'),
        $file_path_origin,
        env('S3_BUCKET_DEST'),
        $file_path_dest,
        'public-read'
    );
} catch(\Exception $e) {
    dd($e->getMessage());
}

记住 Laravel 的 S3 文件系统使用 SDK aws-s3-v3 因此,您搜索 aws-s3-v3 的库以查看 Laravel 包装器具有哪些功能。

因此,在该示例中,我获得了 aws-s3 的客户端 Class,因此我在文档中发现,使用此 class,我可以将文件从一个存储桶移动到另一个。

S3 Php Documentation - Client Class - Copy Method

对于Laravel > 5.6

 try {
        // creat two disk s3 and s3new 
        $fs = Storage::disk('s3')->getDriver();
        $stream = $fs->readStream('file_path/1.jpg');
        $new_fs = Storage::disk('s3new')->getDriver();
        //will create new folder damages if not available 
        $new_fs->writeStream(
            'damages/newfile.jpg',$stream
        );
    } catch(\Exception $e) {
        dd($e->getMessage());
    }