Today I am going to discuss on a topic “upload file to Amazon AWS s3 using laravel5”.Now a days people are using s3 or google drive or Dropbox to store their file instead of their own server.So if you are using laravel 5 in your application, It is very easy to implement s3 as storage disk in your system.
So let’s start.
The first thing we need to use the Filesystem contract and the Request class in our controller.
use Illuminate\Http\Request; use Illuminate\Contracts\Filesystem\Filesystem;
Now create a file upload form.
<form action="{{url('upload')}}" method="post"> <input type="file" name="file"> <input type="submit" name="submit" value="Upload"> </form>
Now create a route with name upload.
Route::post('upload','UploadController@upload');
Before using s3 class , Remember to keep your API Key and Secret Key and bucket and region in your .env fileand load them as an environment variable, like so:
's3' => [ 'driver' => 's3', 'key' => env('S3_KEY'), 'secret' => env('S3_SECRET'), 'region' => env('S3_REGION'), 'bucket' => env('S3_BUCKET'), ],
Now in your upload controller use the Filesystem class and Request class.Now use put method to upload the file in s3.
public function upload(Request $request) { $image = $request->file('file'); $fileName = $image->getClientOriginalExtension(); $filePath = '/directory/' . $fileName; Storage::disk('s3')->put($filePath, file_get_contents($image), 'public'); }
If you want to list content of a directory use the following method.
Storage::disk('s3')->listContents($directory,true);
Here $directory is the directory name and second parameter is for recursive method.