Saturday, October 1, 2016

Laravel 5.x Store Uploaded Files to Amazon S3

Recently in one of my Laravel 5.2 project, we used Amazon s3 to store static files and user uploaded files. So here in this blog I am going to explain how to do this.

1) First of all install following plugin through composer.

composer require league/flysystem-aws-s3-v3 ~1.0

2) Now add your S3 credentials to your environment (.env file)

S3_KEY=YOUR_KEY
S3_SECRET=YOUR_SECRET
S3_REGION=YOUR_REGION
S3_BUCKET=YOUR_BUCKET

3) Open config.filesystems.php and configure s3 driver as follow.

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

4) Now open controller where you have code to manage uploaded file and add following dependency.

use Illuminate\Contracts\Filesystem\Filesystem;

5) Use following code to store your file to S3.

$image = $request->file('user_uploaded_image');
$imageFileName = time() . '.' . $image->getClientOriginalExtension();
$s3 = \Storage::disk('s3');
$filePath = '/mypath'/.$imageFileName;
$s3->put($filePath, file_get_contents($image), 'public');
$uploadedFileS3Path = 'https://'.env('S3_BUCKET').'/'.$filePath;

Please note in my case I configured S3 bucket to be direct URL of uploaded file. In case your case if you have not configured it then your path will be as follow.

$uploadedFileS3Path = 'http://s3-'.env('S3_REGION').'.amazonaws.com/'.env('S3_BUCKET').'/'.$filePath;

This path you can use to display file and you can store it to database as well.


Special Case 

If you are using it in localhost using XAMPP in your windows system. You have to do following few steps.

Download certificate pem file from this link. https://curl.haxx.se/ca/cacert.pem and store it to some where in your C drive or whatever drive you have your xampp installed.

For example I put it in  C:\code\cacert.pem

Now open your php.ini file and bottom of the file add following line.

curl.cainfo = C:\code\cacert.pem

That's it and it will work in your local environment too. Hope this helps you.

No comments:

Post a Comment