- vừa được xem lúc

Upload file với filepond.js và laravel 8

0 0 6

Người đăng: Trường Trần Văn

Theo Viblo Asia

Với filepond.js là 1 thư viện upload ảnh khá tuyệt vời và tài liệu về nó cũng khá nhiều. Cũng có khá nhiều video hướng dẫn kết hợp với laravel, nhưng mình thấy chưa ai hướng dẫn về cách upload theo dạng encode khi chúng ta dùng submit form.

Dưới đây mình sẽ hướng dẫn chi tiết nhé:

  1. Trong code HTML của bạn, tạo một form để gửi request POST đến route submit_form:
<form action="{{ route('submit_form') }}" method="POST" enctype="multipart/form-data"> @csrf <label for="field1">Field 1:</label> <input type="text" name="field1" id="field1"> <label for="field2">Field 2:</label> <input type="text" name="field2" id="field2"> <input type="file" name="filepond" id="filepond"> <button type="submit">Submit</button>
</form> 

và đăng ký thêm plugins endcode

FilePond.registerPlugin( FilePondPluginFileEncode
)
FilePond.create(document.querySelector('#filepond'))
  1. Trong backend

Tạo route:

Route::post('/submit-form', 'App\Http\Controllers\FormController@submitForm')->name('submit_form'); 

Tạo controller:

public function submitForm(Request $request){ $file = $request->input('filepond'); // Giải mã file $file = json_decode($file, true); $fileContent = base64_decode($file['data']); $filePath = $file['name']; Storage::put($filePath, $fileContent); return $filePath; }

Trong đó, chúng ta sử dụng hàm json_decode để chuyển đổi chuỗi JSON sang một mảng trong PHP, sau đó giải mã các file bằng phương thức base64_decode. Cuối cùng, chúng ta lưu các file đã giải mã vào disk bằng phương thức put của đối tượng Storage.

Bình luận

Bài viết tương tự

- vừa được xem lúc

[AWS S3 Laravel] Cách upload nhiều file lên S3 đồng thời để tăng tốc độ upload tới X lần

Mở đầu:. Hi anh em, cũng lâu lắm không viết bài để chia sẻ cũng như cũng cố những thứ đã học được, hôm nay tình cờ tìm được cái mà bản thân thấy cũng hay hay, ho ho (yay) muốn chia sẻ tới mọi người.

0 0 102