In this tutorial, you will learn how to upload an image S3 bucket using PHP/Laravel
I assume you have installed laravel in your server.
Install S3 dependencies in laravel
composer require league/flysystem-aws-s3-v3~1
Update .env file
AWS_ACCESS_KEY_ID=AKIA4BIXXXXXXXXXXX
AWS_SECRET_ACCESS_KEY=Ff8J1EQ74YowQxOhWxxxxxxxxxxxxxxx2
AWS_DEFAULT_REGION=ap-south-1
AWS_BUCKET=demo.codingx.in
Route:(web.php)
Route::get('/fileupload','FileUploadController@index');
Route::post('/save-image','FileUploadController@saveImage');
View:(fileupload.blade.php)
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>File Upload to S3</title>
</head>
<body>
<form method="POST" action="/save-image" enctype="multipart/form-data">
@csrf
<input type="file" name="image">
<button type="submit">Upload</button>
</form>
</body>
</html>
Controller:(FileUploadController.php)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class FileUploadController extends Controller
{
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('fileupload');
}
public function saveImage(Request $request)
{
$this->validate($request,[
'image' => 'required|image|max:2048'
]);
if($request->hasFile('image')){
$file = $request->file('image');
$name = time().$file->getClientOriginalName();
$filepath = $name;
Storage::disk('s3')->put($filepath,file_get_contents($file));
}
return back()->with('success', 'Image uploaded successfully');
}
}
Top comments (0)