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

4.7k views Asked by At

I have objects in one bucket that I occasionally need to transfer to a second bucket in Amazon S3. I'm using Laravel 5.3 with Flysystem to manage those buckets.

One solution is to download the images to my server and then upload it to the other bucket but this seems like a waste of time/bandwidth since the file exists in S3 and is getting moved within S3. Can this be done within Flysystem or will I need to directly use Amazon's API?

3

There are 3 answers

3
Link.de On BEST ANSWER

You can use the FilesystemAdapter move function to move a file:

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

I have found the solution. Here is my code:

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

Remember S3 filesystem of Laravel uses the SDK aws-s3-v3 therefore, you search the libraries of aws-s3-v3 to see what functions the Laravel wrapper has.

So, in the example, I get the Client Class of aws-s3 so I found out in the documentation that, with this class, I can move a file from one bucket to another.

S3 Php Documentation - Client Class - Copy Method

1
Furquan On

For 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());
    }