How to Upload, download, remove Files to Amazon S3 Using Laravel

To upload, download, and remove files to/from Amazon S3 using Laravel, you need to use the `aws-sdk` package, which provides integration with Amazon Web Services (AWS). Follow these steps to achieve this:


Step 1: Install the AWS SDK for PHP

First, you need to install the AWS SDK for PHP using Composer. Open your terminal and run the following command:


composer require aws/aws-sdk-php


Step 2: Set Up AWS Credentials

To use the AWS SDK, you need to set up your AWS credentials. You can do this by adding your AWS access key ID and secret access key to your `.env` file:


AWS_ACCESS_KEY_ID=your_access_key_id

AWS_SECRET_ACCESS_KEY=your_secret_access_key

AWS_DEFAULT_REGION=your_aws_default_region

AWS_BUCKET=your_s3_bucket_name


Replace the placeholders with your actual AWS credentials and bucket name.


Step 3: Upload Files to Amazon S3

In your Laravel code, you can use the `Storage` facade to interact with Amazon S3. To upload files, use the `put` method:


use Illuminate\Support\Facades\Storage;

use Illuminate\Http\Request;


public function upload(Request $request)

{

    if ($request->hasFile('file')) {

        $file = $request->file('file');

        $filePath = $file->store('uploads', 's3');


        return "File uploaded to Amazon S3: " . Storage::disk('s3')->url($filePath);

    }


    return "No file selected for upload.";

}


Step 4: Download Files from Amazon S3

To download files from Amazon S3, you can use the `url` method of the `Storage` facade to generate a temporary URL that provides access to the file:


use Illuminate\Support\Facades\Storage;


public function download($filename)

{

    $url = Storage::disk('s3')->url('uploads/' . $filename);


    return redirect()->away($url);

}


Step 5: Remove Files from Amazon S3

To remove files from Amazon S3, you can use the `delete` method:


use Illuminate\Support\Facades\Storage;


public function remove($filename)

{

    Storage::disk('s3')->delete('uploads/' . $filename);


    return "File removed from Amazon S3.";

}


That's it! With these steps, you can now upload, download, and remove files from Amazon S3 using Laravel and the AWS SDK for PHP. Ensure that you have set up the correct AWS credentials and bucket permissions for smooth operations.