Laravel s3 File Upload Tutorial With Example

In this example, I will explain to you how to do Laravel s3 File Upload Upload Tutorial With Example. We use laravel 5.6 and Amazon s3 package for upload file or image to aws s3. Laravel gives a powerful filesystem abstraction thanks to the Flysystem PHP package by Frank de Jonge. The Laravel Flysystem combination provides easy to use drivers for working with local filesystems, Amazon S3, and Rackspace Cloud Storage. Even better, it’s amazingly to change between these storage options as the API rests the same for each system. If you want to keep your files like image, docs(pdf, docs), video or audio files on Amazon S3 server and access like CDN. So Laravel FileSystem provides to the simple way to upload files in amazon s3 server and you also get file url and remove it.

Laravel s3 File Upload Tutorial With Example

We are going to Configure Laravel Project.

#1: Install Laravel Project

Install Laravel 5.6 Project by the typing following command.

$ composer create-project --prefer-dist laravel/laravel laravels3fileupload

#2: Install s3 package

First, install the s3 package via the Composer package manager.

composer require league/flysystem-aws-s3-v3

#3: Setup s3 bucket

We use amazon s3 to store our images. First, we need to sign up for Amazon. You should follow this link to signup.  After successfully signing you can create your bucket. You can see below image for more clarification.

Laravel s3 file upload example

Now we want to generate bucket policy so move to this link http://awspolicygen.s3.amazonaws.com/policygen.html 

You can see the page like this.

Laravel s3 file upload tutorial

Inside bucket, you create one folder called images.

Then you generate policy and copy paste into bucket policy. You can see below screenshot.

Laravel amazon s3 file upload example

We have added bucket policy now I already start uploading images to the folder which can be publicly accessible.

#4: Setup Cloud Storage

Don’t forget to put your API Key and Secret Key in your .env file. You can add the following field in your .env file.

1.Access Key

2.Secret Access Key

3.Region

4. Bucket

//.env

AWS_ACCESS_KEY_ID=xxxx
AWS_SECRET_ACCESS_KEY=xxxx 
AWS_DEFAULT_REGION=ap-south-1
AWS_BUCKET=laravelfileupload

You can obtain access key and secret access key from My security Credentials. You can see the page looks like below image.

Laravel amazon s3 file upload tutorial

Then go to the user, and a create user after you can generate credentials.

#5: Create a View File

Create a file in resources/views/fileupload.blade.php and put the following code in it.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel s3 File Upload Tutorial With Example</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">   
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>    
  </head>
  <body>
    <div class="container">
      <h2>Laravel s3 File Upload Tutorial With Example</h2><br/>
      @if (\Session::has('success'))
      <div class="alert alert-success">
        <p>{{ \Session::get('success') }}</p>
      </div><br />
     @endif
     @if (count($errors) > 0)
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
          @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif
      <form method="post" action="{{url('fileupload')}}" enctype="multipart/form-data">
        @csrf
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <input type="file" name="image">    
         </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <button type="submit" class="btn btn-success">Upload</button>
          </div>
        </div>
      </form>
    </div>
  </body>
</html>

#6: Create a Controller and route

php artisan make:controller FileUploadController

It will build a controller file called FileUploadController.php.

Add following code to the controller.

//FileUploadController.php

 public function create()
    {
        return view('fileupload');
    }

#7: Define Route

We register all route in a web.php file.

Route::get('fileupload','FileUploadController@create');
Route::post('fileupload','FileUploadController@fileUpload');

Laravel cloud file upload example

#8: Define a function to upload an image

We create a function in FileUploadController called imageUpload(). 

Now we need to create a new S3 Filesystem instance, define a path related to our bucket, and upload the file. We will use the put() method and pass three parameters.

  1. File path relative to your bucket
  2. The contents of the file
  3. Permission of the file (optional)
//FileUploadController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Storage;

class FileUploadController extends Controller
{
    public function create()
    {
        return view('fileupload');
    }
    public function fileUpload(Request $request)
    {
        $this->validate($request, ['image' => 'required|image']);
        if($request->hasfile('image'))
         {
            $file = $request->file('image');
            $name=time().$file->getClientOriginalName();
            $filePath = 'images/' . $name;
            Storage::disk('s3')->put($filePath, file_get_contents($file));
            return back()->with('success','Image Uploaded successfully');
         }
    }
}

You can see below image that file has been uploaded successfully in Amazon s3.

Laravel cloud file upload tutorial

Finally, Our Laravel s3 File Upload Tutorial With Example is over. Thanks for taking.

Add a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.