How use S3 in AWS

administrator

Administrator
Nhân viên
9 Tháng tám 2021
87
0
6
Step 1: Create S3 Bucket

First you need to create bucket and user so let's follow bellow step:

aws-test2.jpg

1. Go to Amazon Web Service Console and Login.
2. Click on S3 from Service Lists
3. Click on "Create Bucket" button and you will found bellow forms. you can enter your bucket name there.
4. Create Create IAM User. Click here to create IAM User.
5. Click on "Create User" button as bellow show you.
6. Next Add User Name and select "Programmatic access" from access type. then click on next.
7. Next Select “Attach Existing Policy Directly” and choose "AmazonS3FullAccess" from permission link.
8. It's optional so you can skip and click to next.
9. You can view user details and then click on "Create User" button.
10. Now you will see created user in link. there is a "Access Key ID" and "Secret Access Key" that we need on .env files.
Mã:
AWS_ACCESS_KEY_ID=AKIAVAEWWDTDY...
AWS_SECRET_ACCESS_KEY=Zp/wgwj46SAC....
AWS_DEFAULT_REGION=us-east-2
AWS_BUCKET=itsolutionstuff-bucket
AWS_USE_PATH_STYLE_ENDPOINT=false
 
Chỉnh sửa lần cuối:

administrator

Administrator
Nhân viên
9 Tháng tám 2021
87
0
6
Step 2: Install Laravel

Mã:
composer create-project --prefer-dist laravel/laravel blog

Step 3: install s3 composer package by using following command

Mã:
composer require --with-all-dependencies league/flysystem-aws-s3-v3 "^1.0"

Step 4: Add .env

Mã:
AWS_ACCESS_KEY_ID=AKIAVAEWWDTDY...
AWS_SECRET_ACCESS_KEY=Zp/wgwj46SAC....
AWS_DEFAULT_REGION=us-east-2
AWS_BUCKET=itsolutionstuff-bucket
AWS_USE_PATH_STYLE_ENDPOINT=false

Step 5: routes/web.php

Mã:
<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\UploadController;


Route::get('upload', [ UploadController::class, 'Upload' ])->name('upload');
Route::post('upload', [ UploadController::class, 'UploadPost' ])->name('upload.post');

Step 6: app/Http/Controllers/UploadController.php

Mã:
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UploadController extends Controller
{
     /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function upload()
    {
        return view('upload');
    }
  
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function UploadPost(Request $request)
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);
  
        $fileUpload = $request->file;
        $typeFile = $fileUpload->extension();
       
        $fileFullName = $fileUpload->getClientOriginalName(); 
        $fileName = str_replace('.' . $typeFile, '', $fileFullName);
        //Save data on s3
        //$path = Storage::disk('s3')->makeDirectory($fileName);
        $path = Storage::disk('s3')->put($fileName, $request->file);
        $path = Storage::disk('s3')->url($path);
        return view('welcome', [
        'title' => 'Upload success! File: '. $path]);
  
        $path = Storage::disk('s3')->put('images', $request->image);
        $path = Storage::disk('s3')->url($path);

        /* Store $imageName name in DATABASE from HERE */
  
        return back()
            ->with('success','You have successfully upload image.')
            ->with('image', $path);
    }
}

Step 7: resources/views/upload.blade.php

Mã:
<!DOCTYPE html>
<html>
<head>
    <title>laravel File Uploading with Amazon S3 - ItSolutionStuff.com.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
  
<body>
<div class="container">
  
    <div class="panel panel-primary">
      <div class="panel-heading"><h2>laravel File Uploading with Amazon S3 - ItSolutionStuff.com.com</h2></div>
      <div class="panel-body">
  
        @if ($message = Session::get('success'))
        <div class="alert alert-success alert-block">
            <button type="button" class="close" data-dismiss="alert">×</button>
                <strong>{{ $message }}</strong>
        </div>
        <img src="{{ Session::get('image') }}">
        @endif
  
        @if (count($errors) > 0)
            <div class="alert alert-danger">
                <strong>Whoops!</strong> There were some problems with your input.
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
  
        <form action="{{ route('upload.post') }}" method="POST" enctype="multipart/form-data">
            @csrf
            <div class="row">
  
                <div class="col-md-6">
                    <input type="file" name="image" class="form-control">
                </div>
  
                <div class="col-md-6">
                    <button type="submit" class="btn btn-success">Upload</button>
                </div>
  
            </div>
        </form>
  
      </div>
    </div>
</div>
</body>

</html>

S3 Uploaded Image:
 
Chỉnh sửa lần cuối:

administrator

Administrator
Nhân viên
9 Tháng tám 2021
87
0
6
How Public file after upload?
Go: S3 -> Bucket -> Permissions -> Bucket policy, add code:
Mã:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::videostream-demo/*"
        }
    ]
}

videostream-demo is bucket