Wednesday, August 3, 2016

How to download a file grom S3 with Laravel

Today let's explain how to download a file from S3 using laravel. Next time I will explain how to upload the file.

1) Set up the bucket name. Ex. YOUR_BUCKET_NAME

2) Set up the bucket policy

{
  "Id": "PolicyXXXXXX",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "XXXXXX",
      "Action": [
        "s3:GetObject"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::testfcce/*",
      "Principal": "*"
    }
  ]
}
You can use the AWS policy generator for that:
http://awspolicygen.s3.amazonaws.com/policygen.html

3) Generate a credentials to have access to the bucket (if you don't have)

4) Change the config/filesystems.php to

        's3' => [
            'driver' => 's3',
            'key'    => env('S3_KEY'),
            'secret' => env('S3_SECRET'),
            'region' => env('S3_REGION'),
            'bucket' => env('S3_BUCKET'),
        ],

5) Add the keys to the .env file

S3_USER=YOUR_USER_NAME
S3_KEY=YOUR_KEY
S3_SECRET=YOUR_SECRET
S3_REGION=eu-central-1
S3_BUCKET=YOUR_BUCKET_NAME

6) Example how to check if a file called image001.jpg is in the bucket and in positive case get the URL

$s3 = Storage::disk('s3');

if ($s3->exists('image001.jpg'))
{
    $bucket = 'YOUR_BUCKET_NAME';

    return $s3->getDriver()->getAdapter()->getClient()->getObjectUrl($bucket, 'image001.jpg');
}


References URLs:

https://return-true.com/uploading-directly-to-amazon-s3-from-your-laravel-5-application/
http://www.server180.com/2016/01/upload-files-to-s3-using-laravel-52.html
https://chrisblackwell.me/upload-files-to-aws-s3-using-laravel/

Best

No comments:

Post a Comment