Xử Lý Image Upload – Laravel

0

Upload hình ảnh trong laravel là công việc thường xuyên hay gặp trong laravel,hầu như dự án nào cũng sẽ có,trong bài viết này mình sẽ chia sẻ cho các bạn về xử lý upload hình ảnh trong Laravel.Khỏi vòng vo nữa,triển khai thôi :))

Bước 1: Tạo Routes

Đầu tiên ta vào routes/web.php

Route::get('image-upload', 'ImageUploadController@imageUpload')->name('image.upload');
Route::post('image-upload', 'ImageUploadController@imageUploadPost')->name('image.upload.post');

Bước 2:Xử lý upload trong Controller

Đây là phần quan trọng nhất, và phần này ta sẽ thực thi tại Controller.

Về Validator

Mình có gợi ý như sau:

  • Vì trên kia đã accept image, nhưng ko có nghĩa là an toàn bởi vì hiện tại các browser chỉ cần F12 là bỏ dc dòng đó. Chúng ta cần phải check 1 lần nữa.
  • Không chỉ check file type, chúng ta còn fải check giới hạn upload file size là bao nhiêu.

app/Http/Controllers/ImageUploadController.php

<?php
   
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class ImageUploadController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function imageUpload()
    {
        return view('imageUpload');
    }
  
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function imageUploadPost(Request $request)
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);
  
        $imageName = time().'.'.$request->image->extension();  
   
        $request->image->move(public_path('images'), $imageName);
   
        return back()
            ->with('success','You have successfully upload image.')
            ->with('image',$imageName);
   
    }
}

Bước 4: Tạo tệp Blade

Ở bước cuối cùng, chúng ta cần tạo tệp imageUpload.blade.php và trong tệp này, chúng ta sẽ tạo form upload

==>Chú ý form phải có enctype=“multipart/form-data”

<!DOCTYPE html>
<html>
<head>
    <title>laravel  image upload example</title>
    <link rel="stylesheet" href="http://getbootstrap.com/dist/css/bootstrap.css">
</head>
  
<body>
<div class="container">
   
    <div class="panel panel-primary">
      <div class="panel-heading"><h2>laravel  image upload example</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="images/{{ 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('image.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>
Leave A Reply

Your email address will not be published.