Chức năng upload file hay hình ảnh là một chức năng rất phổ biến, hầu hết các dự án đều có chức năng này.

Đa số các nhà phát triển khi thực hiện chức năng upload file, thường sẽ sử dụng cách làm như sơ đồ dưới đây:

Khi upload lên server, bạn có thể upload file vào thư mục có thể truy cập từ trình duyệt chẳng hạn /public/uploads và mọi thứ đều rất tuyệt vời.

Rồi đến một ngày trời mưa giông bão, tôi ngồi xuống bên cạnh laptop của mình, bắt đầu search google và một thế lực vô hình nào đó đã giúp tôi biết đến dịch vụ S3 của AWS, tôi bắt đầu tìm hiểu và thử nghiệm trong dự án của mình.

Lúc đó, trong đầu của tôi đã nghĩ đến ý tưởng rất đơn giản nhất là tôi upload file lên server của mình và từ đó sao chép file từ server của mình lên S3, cụ thể là tôi sử dụng Laravel Storage để upload file.

Nhưng sau này, trong một buổi seminar của team tôi trên công ty, thì tôi nhận ra được đây là một điều sai lầm.

Vì để có thể upload file lên S3 của AWS, tôi phải thao tác file upload đó 2 lần, đồng thời tôi phải tốn thêm chi phí liên quan đến server để có thể upload được những file có dung lượng lớn, có thể gia tăng thêm độ trễ mà bất kì người dùng nào cũng cảm thấy rất khó chịu khi trải nghiệm sản phẩm của bạn.

Làm sao tôi có thể sửa chữa sai lầm của mình?

Giả sử, ứng dụng của bạn đã setting mọi thứ liên quan đến S3 để lưu trữ file cho ứng dụng của bạn.

Đồng thời bạn cần setting thêm Cross-origin resource sharing cho Bucket S3 của bạn.

Dưới đây là đoạn Json, tôi setting Cross-origin resource sharing trong bài viết này:

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "PUT"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [],
        "MaxAgeSeconds": 3000
    }
]

Đầu tiên, bạn chạy lệnh sau để tạo ra controller nhằm thực hiện nhiệm vụ tạo ra presigned url cho client thực hiện upload file.

php artisan make:controller S3PresignedUrlController

Sau đó, bạn hãy chỉnh sửa S3PresignedUrlController.php như sau:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class S3PresignedUrlController extends Controller
{
    public function index(Request $request)
    {
        if ($request->name) {
            return response()->json([
                'error'     => false,
                'url'       => $this->get_amazon_url(request('name')),
                'additionalData' => [
                    // Uploading many files and need a unique name? UUID it!
                    //'fileName' => Uuid::uuid4()->toString()
                ],
                'code'      => 200,
            ], 200);
        }     
        return response()->json([
            'error'     => true,
            'message'   => [
                'name' => 'The name field is required.'
            ],
            'code'      => 400,
        ], 400);   
    }

    private function get_amazon_url($name)
    {
        $client = Storage::disk('s3')->getClient();
        $expiry = "+90 minutes";
        $command = $client->getCommand('PutObject', [
            'Bucket' => config('filesystems.disks.s3.bucket'),
            'Key'    => $name,
        ]);
        $request = $client->createPresignedRequest($command, '+20 minutes');
        return (string)$request->getUri();
    }
}

※Lưu ý:
khi ứng dụng của bạn sử dụng Laravel < 9 thì bạn thay đổi mã nguồn sau:

$client = Storage::disk('s3')->getClient();

⥥Thành mã nguồn này⥥

$client = Storage::disk('s3')->getDriver()->getAdapter()->getClient();

Tiếp theo, bạn hãy chỉnh sửa file routes.php như sau:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\S3PresignedUrlController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});
Route::get('/s3-presigned-url', [S3PresignedUrlController::class, 'index']);

Cuối cùng, bạn hãy mở file welcome.php và chỉnh sửa như sau:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="ManhDan Blogs">
        <meta name="author" content="ManhDan Blogs">
        <meta name="generator" content="ManhDan Blogs 0.84.0">
        <title>ManhDan Blogs</title>
        <link rel="icon" href="https://manhdandev.com/web/img/favicon.webp" type="image/x-icon"/>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
        <link href="https://unpkg.com/[email protected]/dist/dropzone.css" rel="stylesheet" type="text/css" />
    </head>
<body>
<div class="col-lg-8 mx-auto p-3 py-md-5">
    <header class="d-flex align-items-center pb-3 mb-5 border-bottom">
        <a href="https://manhdandev.com" class="d-flex align-items-center text-dark text-decoration-none" target="_blank">
            <img src="https://manhdandev.com/web/img/logo.webp" width="100px" height="100px">
        </a>
    </header>
    <main>
        <h1>Laravel, Presigned URLs S3 & Dropzone (Basic)</h1>
        <div class="mb-5">
            <form class="form" action="#" method="post">
                <div class="fv-row">
                    <div class="dropzone" id="dropzone">
                        <div class="dz-message needsclick">
                            <i class="bi bi-file-earmark-arrow-up text-primary fs-3x"></i>
                            <div class="ms-4">
                                <h3 class="fs-5 fw-bolder text-gray-900 mb-1">Drop files here or click to upload.</h3>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </main>
    <footer class="pt-5 my-5 text-muted border-top">
        &copy;Copyright &copy;2021 All rights reserved | This template is made with
        <i class="fa fa-heart-o"></i> by <a href="https://www.facebook.com/beater.2708" rel="noopener" target="_blank">ManhDan</a>
    </footer>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/dropzone-min.js"></script>
<script>
    var dropzone = new Dropzone('#dropzone',{
    url: '#',
    method: 'put',
    autoQueue: false,
    autoProcessQueue: false,
    init: function() {
        /*
            When a file is added to the queue
                - pass it along to the signed url controller
                - get the response json
                - set the upload url based on the response
                - add additional data (such as the uuid filename) 
                    to a temporary parameter
                - start the upload
        */
        this.on('addedfile', function(file) {
            fetch('/s3-presigned-url?name='+file.name, {
                method: 'get'
            }).then(function (response) {
                return response.json();
            }).then(function (json) {
                dropzone.options.url = json.url;
                file.additionalData = json.additionalData;
                dropzone.processFile(file);
            });
        });

        /*
            When uploading the file
                - make sure to set the upload timeout to near unlimited
                - add all the additional data to the request
        */
        this.on('sending', function(file, xhr, formData) {
            xhr.timeout = 99999999;
            for (var field in file.additionalData) {
                formData.append(field, file.additionalData[field]);
            }
        });

        /*
            Handle the success of an upload 
        */
        this.on('success', function(file) {
            // Let the Laravel application know the file was uploaded successfully 
        });
    },
    sending: function(file, xhr) {
        var _send = xhr.send;
        xhr.send = function() {
            _send.call(xhr, file);
        };
    },
});
</script>
</body>
</html>

Sau đây là sơ đồ upload file lên S3 của AWS khi bạn sử dụng Presigned URLs S3:

Trải nghiệm Presigned URLs S3 & Dropzone trong Laravel

Tài liệu tham khảo:

https://jcode.me/laravel-dropzone-the-right-way

https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html

CÓ THỂ BẠN QUAN TÂM

Integrating elFinder into TinyMCE 6 in Laravel

Integrating elFinder into TinyMCE 6 in Laravel

TinyMCE TinyMCE là một trình soạn thảo WYSIWYG được xây dựng trên nền tảng Javascript, được phát triển dưới dạng mã nguồn mở theo giấy phép MIT bởi Tiny Technologies Inc. TinyMCE cho phép người d...

Encrypted HTTP Live Streaming with Laravel FFMpeg

Encrypted HTTP Live Streaming with Laravel FFMpeg

HTTP Live Streaming (HLS)  HTTP Live Streaming (HLS) là một trong những giao thức phát trực tuyến video được sử dụng rộng rãi nhất . Mặc dù nó được gọi là HTTP "live" streaming, nhưng nó được sử dụn...

Laravel Socialite Login With Google

Laravel Socialite Login With Google

Google Google là một công cụ tìm kiếm trên internet. Nó sử dụng một thuật toán độc quyền được thiết kế để truy xuất và sắp xếp các kết quả tìm kiếm nhằm cung cấp các nguồn dữ liệu đáng tin cậy và ph...

Laravel Facades

Laravel Facades

Facade là gì? Chúng ta có thể hiểu Facade là mặt tiền và mặt trước của một tòa nhà hay bất cứ thứ gì. Tầm quan trọng của Facade là chúng có thể dễ nhận thấy và nổi bật hơn, tương tự như vậy, thì...

Efficient Laravel PDF Export for Large Datasets

Efficient Laravel PDF Export for Large Datasets

Xuất file PDF là một tính năng quan trọng của nhiều ứng dụng web, đặc biệt là các trang thương mại điện tử, giúp người dùng tạo và lưu trữ các bản báo cáo, hóa đơn, v.v.  Tuy nhiên, khi phải xử lý...

Laravel Socialite Login With Gitlab

Laravel Socialite Login With Gitlab

GitLab GitLab là kho lưu trữ Git dựa trên web cung cấp các kho lưu trữ mở và riêng tư miễn phí, các khả năng theo dõi vấn đề và wiki. Đây là một nền tảng DevOps hoàn chỉnh cho phép các chuyên gia...

Defer in Laravel: Push Tasks to the Background

Defer in Laravel: Push Tasks to the Background

Deferred Functions trong Laravel Các phiên bản Laravel trước version 11, chúng ta thường sử dụng Queued Jobs cho phép thực hiện sắp xếp các tác vụ xử lý background . Nhưng đôi khi có những tác v...

Laravel One to Many Eloquent Relationship

Laravel One to Many Eloquent Relationship

One to Many Relationship được sử dụng trong trường hợp một dữ liệu của một bảng được liên kết với một hoặc nhiều dữ liệu ở bảng khác. Ví dụ, một bài post có thể có nhiều comment. Vì vậy, trong hướn...

Laravel Controllers

Laravel Controllers

Trong mô hình MVC, chữ "C" là từ viết tắt của Controller và nó đóng vai trò rất quan trọng để phân tích các logic business. Khi người dùng truy cập vào trình duyệt, nó sẽ đi đến route đầu tiên, sau đó...

ManhDanBlogs