AppDividend
Latest Code Tutorials

Laravel Cloud File Upload Tutorial With Example

Laravel s3 File Upload Tutorial

2,291

Get real time updates directly on you device, subscribe now.

Laravel Cloud File Upload Tutorial With Example is the topic, we will discuss today. For this example, we use laravel 5.6 and Amazon s3 package for upload file to aws s3.

Laravel gives a powerful filesystem abstraction thanks to the Flysystem PHP package by Frank de Jonge. The Laravel Flysystem integration provides easy to use drivers for working with local filesystems, Amazon S3, and Rackspace Cloud Storage. Even better, it’s amazingly easy to switch between these storage options as the API rests the same for each system.

Amazon S3 stores data as objects inside resources called “buckets.” You can store as multiple objects as you require within a bucket, and read, write, and delete objects in your bucket. Objects can do up to 5 terabytes in size. You can store images, files or other documents.

Laravel Cloud File Upload Tutorial With Example

We are going to Configure Laravel Project.

Step 1: Download Laravel Project

Establish  Laravel Project by the typing following command.

composer create-project --prefer-dist laravel/laravel cloudimageupload

Step 2: Setup s3 bucket

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

laravel cloud file upload example

Now we need 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 bucket policy

 

Inside bucket, you create one folder called images.

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

laravel s3 file upload tutorial

 

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

Step 3: Setup Cloud Storage

Remember 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=xxxxx
AWS_SECRET_ACCESS_KEY=xxxx
AWS_DEFAULT_REGION=ap-south-1
AWS_BUCKET=laravelimage

You can get access key and secret access key from My security Credentials. You can see the page looks like that.

Related Posts
1 of 39

laravel s3 file upload example

 

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

Step 4: Install s3 package

First, install s3 package via the Composer package manager.

composer require league/flysystem-aws-s3-v3

Step 5: Create a View File

Create a file in resources  >>  views  >>  uploadimage.blade.php and put this following code in it.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel Cloud File Upload Tutorial</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 Cloud File Upload Tutorial</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('createimage')}}" 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>

Step 6: Create a Controller and route

 php artisan make:controller ImageController

It will build a controller file called ImageController.php.

Add following code to the controller.

//Imageontroller.php

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

We register all route in a web.php file.

Route::get('createimage','ImageController@create');
Route::post('createimage','ImageController@imageUpload');

Step 7: Create a function to upload an image

We create a function in ImageController called imageUpload(). 

Now we want to create a new S3 Filesystem instance, define the 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)
//ImageController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Storage;

class ImageController extends Controller
{
    public function create()
    {
        return view('uploadimage');
    }
    public function imageUpload(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 the image that file has been uploaded successfully in Amazon s3.

 

laravel 5.6 s3 file upload tutorial

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

Leave A Reply

Your email address will not be published.

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