Upload và remove hình ảnh trong laravel

upload và remove hình ảnh trong laravel
5/5 - (1 vote)

Chúng ta đã cùng tìm hiểu về cách Upload nhiều ảnh trong laravel bằng ajax trong bài viết trước. Hôm nay chúng ta sẽ nâng cấp lên một chút, đó là upload và remove hình ảnh trong laravel đã upload trước đó trong laravel.

Upload và remove hình ảnh trong laravel như thế nào?

Ở bài Upload nhiều ảnh trong laravel bằng ajax chúng ta có thể upload hình ảnh và xoá được hình ảnh. Tuy nhiên có một nhựơc điểm là nó chỉ có thể xoá được những hình ảnh ở một định dạng nhất định.

Còn ở bài này chúng ta có thể xoá bất cứ hình ảnh nào mà mình đã upload lên trước đó cộng với giao diện upload trực quan và đẹp hơn.

Nguyên lý hoạt động ở đây là sau khi upload hình ảnh lên, chúng ta sẽ lưu trữ các tên file ảnh vào cơ sở dữ liệu. Sau đó từ các tên file này chúng ta sẽ load lên và hiển thị ngược ra ở giao diện người dùng và cho phép người dùng xoá bỏ hình ảnh không mong muốn hoặc upload thêm hình ảnh.

Html giao diện người dùng để upload và remove hình ảnh

Dưới đây là đoạn html cần cho việc hiển thị hình ảnh cũng như remove hình ảnh

<div class="form-group row">
    <label class="col-sm-2 col-form-label">Bill</label>
    <div class="col-sm-10">
        <div class="jquery-upload">
            <div class="jquery-upload-container">
                <div class="jquery-upload-input">
                    <input type="file" name="inputJanodalBill[]" id="uploadFile" accept="image/*" hidden>
                </div>
                <div class="jquery-upload-add">
                    <i class="fas fa-plus"></i>
                    <span>Upload</span>
                </div>
            </div>
        </div>
        <input type="hidden" name="original_image_list" id="original_image_list">
    </div>
</div>

Ở đoạn HTML trên chúng ta sử dụng input type file để upload hình ảnh tuy nhiên không sử dụng atribute multiple vì mục đích của chúng ta là sẽ upload mỗi lần 1 file mà thôi sau đó lưu vào mảng name inputJanodalBill[] và với nhiều input file chúng ta sẽ tạo thành multiple file để tiện cho việc xoá ảnh.

Và chúng ta cũng có thêm một input với type hidden để tải danh sách tên file đã lưu ở cơ sở dữ liệu lên (cái này là dùng cho mục đích xoá file sau này).

Lưu ý: Nếu muốn upload các file như pdf hoặc doc thì bạn thay accept=”image/*” bằng accept=”image/*,application/msexcel,application/msword,application/pdf,”

Javascript xử lý upload và remove ảnh từ giao diện người dùng

Với html ở trên chúng ta chỉ có thể thực hiện được thao tác đơn giản là upload được 1 file vào input chứ không cỏ preview hình ảnh hay thêm xoá gì được.

Vì vậy đoạn javascript này sẽ giúp bạn thêm, preview và remove hình ảnh

<script type="text/javascript">
    $(document).ready(function() {
        $('.jquery-upload-add').click(function() {
            $('#uploadFile').trigger('click');
        });
        $('.jquery-upload-input').on('change', '#uploadFile', function(event) {
            let today = new Date();
            let time = today.getTime();
            let image = event.target.files[0];
            let file_name = event.target.files[0].name;
            let box_image = '<div class="jquery-upload-preview">' +
                '<div class="jquery-upload-delete" data-id=' + time + '>' +
                '<i class="fas fa-trash-alt"></i>' +
                '</div>' +
                '<img src="' + URL.createObjectURL(image) + '" alt="">' +
                '</div>';
            let input_file = '<input type="file" name="inputJanodalBill[]" id="uploadFile"  accept="image/*" hidden>';

            $(this).removeAttr('id');
            $(this).attr('id', time);
            $('.jquery-upload-input').prepend(input_file);
            $('.jquery-upload-container').prepend(box_image);
        });
        $('.jquery-upload-container').on('click', '.jquery-upload-delete', function() {
            let id = $(this).data('id');
            $('#' + id).remove();
            $('.jquery-upload-input').find('#img-' + id).remove();
            $(this).parents('.jquery-upload-preview').remove();
        });
    });
</script>

Với đoạn javascript này mỗi khi ta click vào ô thêm ảnh thì nó sẽ tác động đên input file có id là uploadFile. và khi input file có thay đổi thì đoạn code sẽ xử lý để hiển thị hình ảnh preview và đồng thời nó cũng thêm mới một input file khác để chúng ta có thể tiếp tục tiến hành thêm hình ảnh khác. Trong mỗi hình ảnh được preview sẽ có hình biểu tượng thùng rác bạn có thể xoá hình ảnh mà mình vừa upload lên.

Css làm đẹp cho chúng năng upload và remove hình ảnh trong laravel

Với html và javascript trên thì cơ bản bạn đã có thể upload được hình ảnh nhưng chúng sẽ trông rất xấu vì vậy bạn cần phải nhờ đến sự giúp đỡ của CSS mà tôi chia sẽ dưới đây.

.jquery-upload-container{
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  padding: 10px;
}
.jquery-upload-preview{
  width: 80px;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid rgba(103, 103, 103, 0.39);
  padding: 5px;
  margin:5px;
  position: relative;
}
.jquery-upload-preview img{
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.jquery-upload-delete{
  display: none;
}

.jquery-upload-preview:hover .jquery-upload-delete{
  cursor: pointer;
  position: absolute;
  display: block;
  color: red;
}

.jquery-upload-add{
  width: 80px;
  height: 80px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #fafafa;
  border:1px dashed #ccc;
}
.jquery-upload-add:hover{
  cursor: pointer;
  border-color: #430f70;
}

Xử lý upload và remove hình ảnh trong laravel controller

Cuối cùng cái chúng ta cần phải làm để hoàn thiện được chức năng upload và xoá hình ảnh trong laravel đó là viết controller.

$files = [];
            if($request->hasfile('inputJanodalBill'))
            {
                foreach($request->file('inputJanodalBill') as $file)
                {
                    $name = time().rand(1,100).'.'.$file->extension();
                    $file->move(public_path('uploads/financialbill'), $name);  
                    $files[] = $name;  
                }
            }

            if (isset($request->original_image) && !empty($request->original_image_list)) {
                $files_remove = array_diff(json_decode($request->original_image_list), $request->original_image);
                $files = array_merge($request->original_image, $files);
            } else {
                $files_remove = json_decode($request->original_image_list);
            }
            $request->financial_bill = json_encode($files);
            if(!empty($files_remove)){
                foreach ($files_remove as $file_name) {
                    $file_path = public_path("uploads/financialbill/{$file_name}");
                    if (\File::exists($file_path)) {
                        \File::delete($file_path);
                    }
                }
            }

Bạn bỏ đoạn code trên vào function phù hợp trong controller của bạn, nó sẽ giúp bạn lưu trữ hình ảnh mà bạn tại lên vào thưc mục uploads/financialbill trong public folder.

Và khi lưu dữ liệu vào cơ sở dữ liệu bạn để ý đến $request->financial_bill nhé.

Như vậy là chúng ta đã có một chức năng upload và remove hình ảnh trong laravel rất đẹp cho các dự án của mình.

Giao diện mình dựa theo plugin sau: https://www.jqueryscript.net/form/ajax-file-uploader.html

Để lại bình luận

Email của bạn sẽ được bảo mật.