Search code examples
jquerylaraveldropzone.js

How to Edit and upload existing images with DropZone plugin Laravel JS


I tried to add dropzone to my project to do crud in images. i need to know how to add or remove existing images in server and update the files. i have done the create part but for edit part im stuck. this is my code below to get existing images and upload images.

Dropzone.autoDiscover = false;
    $("#dZUploadEdit").dropzone({ // initialize
        createImageThumbnails: true,
        autoProcessQueue: false,
        uploadMultiple: true,
        parallelUploads: 5,
        addRemoveLinks: true,
        url: "product/" + id, // upload route
        type: "PUT",
        maxFiles: 5,
        data: {
            _token: $('meta[name="csrf-token"]').attr("content")
        },

    

init: function() {  // start of getting existing imahes
            myDropzone = this;
            $.ajax({
                url: "product/images",
                type: "POST",
                data: {
                    id: id,
                    _token: $('meta[name="csrf-token"]').attr("content")
                },
                dataType: "json",
                success: function(response) { // get result
                    $.each(response, function(key, value) {
                        var mockFile = {
                            name: value.name,
                            size: value.size
                        };
                        myDropzone.options.addedfile.call(
                            myDropzone,
                            mockFile
                        );
                        myDropzone.options.thumbnail.call(
                            myDropzone,
                            mockFile,
                            "storage/products/" + value.name
                        );
                        $("[data-dz-thumbnail]").css("height", "120");
                        $("[data-dz-thumbnail]").css("width", "120");
                        $("[data-dz-thumbnail]").css("object-fit", "cover");
                    });
                    // Update selector to match your button
                    $("#update-btn").on("click", function(e) {
                        e.preventDefault();
                        myDropzone.processQueue();
                    });
                    myDropzone.on("sending", function(file, xhr, formData) {
                        // Append all form inputs to the formData Dropzone will POST
                        var data = $("#editForm").serializeArray();
                        $.each(data, function(key, el) {
                            formData.append(el.name, el.value);
                        });
                    });
                }
            });
        },
    

success: function(file, response) {
            file.previewElement.classList.add("dz-success");
            return location.reload();
        },
        error: function(file, errorMessage) {
            errors = true;
            Swal.fire({
                icon: "error",
                title: "Oops...",
                text: "Something went wrong!",
                footer: "Changes are not saved!"
            }).then(result => {
                if (result.value) {
                    return location.reload();
                }
            });
        }
    });

i need to edit existing images and update new images.


Solution

  • This code is written for Laravel blade file :

    @foreach ($product->attachments as $attach)
    <?php $path =  Helper::image_to_base64(asset($attach->url)); ?>
    
    <script>
        $("document").ready(()=>{
            var path = "{{ $path }}";
            var file = new File([path], "{{ $attach->file_name }}", {type: "{{ $attach->mime_type }}", lastModified: {{ $attach->updated_at}}})
            file['status'] = "queued";
            file['status'] = "queued";
            file['previewElement'] = "div.dz-preview.dz-image-preview";
            file['previewTemplate'] = "div.dz-preview.dz-image-preview";
            file['_removeLink'] = "a.dz-remove";
            file['webkitRelativePath'] = "";
            file['width'] = 500;
            file['height'] = 500;
            file['accepted'] = true;
            file['dataURL'] = path;
            file['upload'] = {
                bytesSent: 0 ,
                filename: "{{ $attach->file_name }}" ,
                progress: 0 ,
                total: {{ $attach->file_size }} ,
                uuid: "{{ md5($attach->id) }}" ,
            };
    
            myDropzone.emit("addedfile", file , path);
            myDropzone.emit("thumbnail", file , path);
            // myDropzone.emit("complete", itemInfo);
            // myDropzone.options.maxFiles = myDropzone.options.maxFiles - 1;
            myDropzone.files.push(file);
            console.log(file);
        });
    </script>
    @endforeach