How do I download a file with php and the Amazon S3 sdk?

后端 未结 6 1943
不思量自难忘°
不思量自难忘° 2020-12-15 21:01

I\'m trying to make it so that my script will show test.jpg in an Amazon S3 bucket through php. Here\'s what I have so far:

require_once(\'library/AWS/sdk.cl         


        
6条回答
  •  -上瘾入骨i
    2020-12-15 21:42

    This script downloads all files in all directories on an S3 service, such as Amazon S3 or DigitalOcean spaces.

    1. Configure your credentials (See the class constants and the code under the class)
    2. Run composer require aws/aws-sdk-php
    3. Assuming you saved this script to index.php, then run php index.php in a console and let it rip!

    Please note that I just wrote code to get the job done so I can close down my DO account. It does what I need it to, but there are several improvements I could have made to make it more extendable. Enjoy!


     'latest',
                'region'  => static::CREDENTIALS_REGION,
                'endpoint' => static::CREDENTIALS_ENDPOINT,
                'credentials' => [
                    'key'    => static::CREDENTIALS_API_KEY,
                    'secret' => static::CREDENTIALS_API_KEY_SECRET,
                ],
            ], $args);
    
            $this->client = new S3Client($config);
        }
    
        public function download($destinationRoot) {
            $objects = $this->client->listObjectsV2([
                'Bucket' => static::CREDENTIALS_BUCKET,
            ]);
    
            foreach ($objects['Contents'] as $obj){
    
                echo "DOWNLOADING " . $obj['Key'] . "\n";
                $result = $this->client->getObject([
                    'Bucket' => 'dragon-cloud-assets',
                    'Key' => $obj['Key'],
                ]);
    
                $this->handleObject($destinationRoot . $obj['Key'], $result['Body']);
    
            }
        }
    
        private function handleObject($name, $data) {
            $this->ensureDirExists($name);
    
            if (substr($name, -1, 1) !== '/') {
                echo "CREATING " . $name . "\n";
                file_put_contents($name, $data);
            }
        }
    
        private function ensureDirExists($name) {
            $dir = $name;
            if (substr($name, -1, 1) !== '/') {
                $parts = explode('/', $name);
                array_pop($parts);
                $dir = implode('/', $parts);
            }
    
            @mkdir($dir, 0777, true);
        }
    
    }
    
    $doSpaces = new DOSpaces([
        'endpoint' => 'https://nyc2.digitaloceanspaces.com',
        'credentials' => [
            'key'    => '12345',
            'secret' => '54321',
        ],
    ]);
    $doSpaces->download('/home/myusername/Downloads/directoryhere/');
    

提交回复
热议问题