AWS S3 + Laravel - File Upload, Download, List, and Delete Example
Here’s how you can implement AWS S3 file upload, download, list, and delete functionalities in a Laravel application step-by-step.
1. Setting Up AWS S3
1. Create an AWS Account: If you don't have one, sign up for an AWS account.
2. Create an S3 Bucket:
- Log in to the AWS Management Console.
- Navigate to the S3 service.
- Click "Create bucket."
- Provide a unique bucket name and choose an appropriate region.
- Configure access permissions as needed (e.g., public or private).
2. Install AWS SDK for Laravel
Install the AWS S3 package via Composer:
composer require league/flysystem-aws-s3-v3 "^3.0"
3. Configure AWS S3 in Laravel
1. Set up environment variables in the .env file:
AWS_ACCESS_KEY_ID=your-access-key
AWS_SECRET_ACCESS_KEY=your-secret-key
AWS_DEFAULT_REGION=your-region
AWS_BUCKET=your-bucket-name
2. Update config/filesystems.php to include the S3 configuration:
'disks' => [
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'), // Optional
'endpoint' => env('AWS_ENDPOINT'), // Optional
],
],
4. Implement File Operations
Use Laravel's Storage facade for file operations:
Upload a File
use Illuminate\Support\Facades\Storage;
public function uploadFile(Request $request)
{
$request->validate([
'file' => 'required|file|max:2048', // Example validation
]);
$file = $request->file('file');
$path = $file->store('folder-name', 's3'); // 'folder-name' is optional
$url = Storage::disk('s3')->url($path);
return response()->json(['message' => 'File uploaded successfully', 'url' => $url]);
}
List Files
public function listFiles()
{
$files = Storage::disk('s3')->files('folder-name'); // 'folder-name' is optional
return response()->json(['files' => $files]);
}
Download a File
public function downloadFile($filename)
{
$file = Storage::disk('s3')->get($filename);
return response($file, 200)
->header('Content-Type', 'application/octet-stream')
->header('Content-Disposition', 'attachment; filename="' . basename($filename) . '"');
}
Delete a File
public function deleteFile($filename)
{
$result = Storage::disk('s3')->delete($filename);
if ($result) {
return response()->json(['message' => 'File deleted successfully']);
} else {
return response()->json(['message' => 'File deletion failed'], 500);
}
}
5. Route Configuration
Define the routes in routes/web.php or routes/api.php:
use App\Http\Controllers\FileController;
Route::post('/upload', [FileController::class, 'uploadFile']);
Route::get('/list', [FileController::class, 'listFiles']);
Route::get('/download/{filename}', [FileController::class, 'downloadFile']);
Route::delete('/delete/{filename}', [FileController::class, 'deleteFile']);