Php laravel Upload file directly to AWS S3 bucket

Viewed 5697

Can anyone help me how to upload a file into aws S3 bucket using PHP laravel. But the file should directly get uploaded into S3 using pre signed URL.

3 Answers

I will try to answer this question. So, there are two ways to do this:

  1. You send the pre-signed URL to Frontend Client and let them upload the file to S3 directly, and once uploaded they notify your server of the same.

  2. You receive the file directly on the server and upload it to S3, in this case, you won't need any pre-signed URL, as you would have already configured the AWS access inside the project.


Since solution 1 is self-explanatory, I will try to explain the solution 2.

Laravel provides Storage Facade for handling filesystem operations. It follows the philosophy of multiple drivers - Public, Local Disk, Amazon S3, FTP plus option of extending the driver.

Step 1: Configure your .env file with AWS keys, you will need the following values to start using Amazon S3 as the driver:

  • AWS Key
  • AWS Secret
  • AWS Bucket Name
  • AWS Bucket Region

Step 2: Assuming that you already have the file uploaded to your server. We will now upload the file to S3 from our server.

If you have mentioned s3 as the default disk, following snippet will do the upload for you:

Storage::put('avatars/1', $fileContents);

If you are using multiple disks, you can upload the file by:

Storage::disk('s3')->put('avatars/1', $fileContents);

We are done! Your file is now uploaded to your S3 bucket. Double-check it inside you S3 bucket.


If you wish to learn more about Laravel Storage, click here.

use Storage;
use Config;

$client = Storage::disk('s3')->getDriver()->getAdapter()->getClient();
$bucket = Config::get('filesystems.disks.s3.bucket');

$command = $client->getCommand('PutObject', [
    'Bucket' => $bucket,
    'Key' => '344772707_360.mp4'  // file name in s3 bucket which you want to access
]);

$request = $client->createPresignedRequest($command, '+20 minutes');

// Get the actual presigned-url
return $presignedUrl = (string)$request->getUri();

We can use 'PutObject' to generate a signed-url for uploading files onto S3.

Make sure this package is insalled:

composer require league/flysystem-aws-s3-v3 "^1.0"

Create access credentials on AWS and set these variables in .env file

AWS_ACCESS_KEY_ID=ORJATNRFO7SDSMJESWMW
AWS_SECRET_ACCESS_KEY=xnzuPuatfZu09103/BXorsO4H/xxxxxxxxxx
AWS_DEFAULT_REGION=ap-south-1
AWS_BUCKET=xxxxxxx
AWS_URL=http://xxxxx.s3.ap-south-1.amazonaws.com/


public function uploadToS3(Request $request)
{
    $file = $request->file('file');
    \Storage::disk('s3')->put(
                    'path/in/s3/filename.jpg',
                    file_get_contents($file->getRealPath())
                );
}

Create credentials here:enter image description here

Related