lipon
lipon

Reputation: 11

Change Dropzone maxFiles Dynamically

I'm trying to dynamically update the MaxFiles property each time a new image is uploaded/deleted. By using the following code its not allowing any image to upload instead of limitize it to maxFiles. And it is not taking the value of the variable maxFile, but when i remove maxFile variable And put a number then it works fine. got source code idea from this Answer.

!function ($) {
"use strict";
var Onyx = Onyx || {};


Onyx = {
    init: function() {
        var self = this,
            obj;

        for (obj in self) {
            if ( self.hasOwnProperty(obj)) {
                var _method =  self[obj];
                if ( _method.selector !== undefined && _method.init !== undefined ) {
                    if ( $(_method.selector).length > 0 ) {
                        _method.init();
                    }
                }
            }
        }
    },

    userFilesDropzone: {
        selector: 'form.dropzone',
        init: function() {
            var base = this,
                container = $(base.selector);

            base.initFileUploader(base, 'form.dropzone');
        },
        initFileUploader: function(base, target) {

            var maxFile = $('.dropzone').attr('data-count');

            var onyxDropzone = new Dropzone(target, {
                url: ($(target).attr("action")) ? $(target).attr("action") : "data.php", // Check that our form has an action attr and if not, set one here
                maxFiles: maxFile, 
                maxFilesize: 5,
                acceptedFiles: ".JPG,.PNG,.JPEG",
            //  previewTemplate: previewTemplate,
            //  previewsContainer: "#previews",
                clickable: true,
                uploadMultiple: false,

            });

            onyxDropzone.on("success", function(file, response) {
                let parsedResponse = JSON.parse(response);
                file.upload_ticket = parsedResponse.file_link;
                var imagecount = $('.dropzone').attr('data-count');
                    imagecount = imagecount - 1;
                    $('.dropzone').attr('data-count', imagecount);
            });
        },
    }
  }
}// JavaScript Document

function openImagePopup(id = null) {
   $(".upload-images").show();
    $.ajax({
        url: 'fetch.php',
        type: 'post',
        data: {id: id},
        dataType: 'json',
        success:function(response) {
            var imagecount = response.counts;
            $('.dropzone').attr('data-count', imagecount);
    }
 });
}  

HTML

<form action="data.php" class="dropzone files-container" data-count="">
   <div class="fallback">
       <input name="file" type="file" multiple />
   </div>
   <input type="hidden" id="imageId" name="imageId">
</form>

Upvotes: 3

Views: 4263

Answers (2)

gaba
gaba

Reputation: 75

After spending a couple of hours of trials and errors I realized using the maxFiles setting from Dropzone is not exactly what is expected in many cases. That setting will only limit uploading files through the explorer / drag&drop, but after reload more files can be uploaded. It also does not reflect any failures to the upload on the serrver side (e.g. file size too big).

Changing the value of the maxFiles setting of an already initialized Dropzone from outside ot it is impossible. For example reseting the number of allowed files after removing some images with ajax will not work.

To really control the number of files that can be uploaded to the server the counting must take place on the server. Then in the Dropzone, in the success function, we should handle the ajax response:

success: function (file, response) {
    var response_data = jQuery.parseJSON(response);
    if(!response_data.success) {
        $(file.previewElement).addClass('dz-error');
        $(file.previewElement).addClass('dz- complete');
        $(file.previewElement).find('.dz-error-message').text(response_data.error);
    }
}

The response is the feedback information provided by the script assigned to the action attribute of the Dropzone <form>, e.g. <form action="/uploader">.

Upvotes: -1

Jonathan Larouche
Jonathan Larouche

Reputation: 992

UPDATED ANSWER

Once instanciated, the Dropzone plugin will remains with the same options unless you change the instance inner options directly.

To change options of a Dropzone, you can do this with the following line:

$('.dropzone')[0].dropzone.options.maxFiles = newValue;

$('.dropzone')[0] returns the first dropzone DOM element

.dropzone.options return the underlying plugin instance options of the Dropzone. You can now change any options directly on this object.

In you case, you will have to change the function that initiate the popup like follow

function openImagePopup(id = null) {
   $(".upload-images").show();
    $.ajax({
        url: 'fetch.php',
        type: 'post',
        data: {id: id},
        dataType: 'json',
        success:function(response) {
            var imagecount = response.counts;
            $('.dropzone')[0].dropzone.options.maxFiles = imagecount;
    }
 });
}

And change the dropzone onSuccess event like this:

onyxDropzone.on("success", function(file, response) {
    let parsedResponse = JSON.parse(response);
    file.upload_ticket = parsedResponse.file_link;
    var imagecount = $('.dropzone')[0].dropzone.options.maxFiles - 1;
    $('.dropzone')[0].dropzone.options.maxFiles = imagecount;
});

As you can see, You can also remove the data-count="" attribute on you element and reuse the value from the plugin instance options.maxFiles

Upvotes: 4

Related Questions