D.Cristi
D.Cristi

Reputation: 177

How to check if there is already an image in dropzone?

I have the following code:

CODE JS:

Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("div#myDrop", {
    url             : "<?php echo $this->serverUrl() . '/profile/ajax/dzupload'; ?>",
    paramName       : 'profilepicture',
    acceptedFiles   : "image/*",
    maxFiles        : 1,
    addRemoveLinks  : true,
    init            : function() {
        this.on("success", function(file, responseText) {

            $('#profilePicture').attr("value", responseText.filename);
            console.log(responseText);
        });

        this.on("maxfilesexceeded", function(file){
            this.removeFile(file);
            alert("You are not allowed to chose more than 1 file!");
        });

        this.on("removedfile", function (file){
            $.ajax({
                method: 'POST',
                url: '<?php echo $this->serverUrl() . '/profile/ajax/dzdelete' ?>',
                data: {
                    area    : 'company-profile',
                    name    : $('#profilePicture').attr('value')
                },
                success: function(result){
                    $('#profilePicture').attr("value", '')
                    console.log(result);
                }
            })
        });
    }
});

      var fileName = $('#profilePicture').val();
      var mockFile = { name: fileName, size: 12345 };
      myDropzone.options.addedfile.call(myDropzone, mockFile);
      myDropzone.options.thumbnail.call(myDropzone, mockFile, "<?php echo $this->serverUrl().'/public/profile/'.'usr'.$practitionerInfo->user_id.'/picture/'.$practitionerInfo->profilepicture ?>");

I would like to check if there is already loaded an image... if not there then lets you add another image until I delete the previous

I tried the following code but it does not work

if(!myDropzone.file.length()){
    //allow to upload file
}else{
   alert("please remove existing file");
}

How can I do this? I hope I was able to explain well.

EDIT:

If you add this code 0 but the picture is added receive default and should be one, right?

console.log(myDropzone.files.length) //return 0

Upvotes: 1

Views: 8259

Answers (1)

twernt
twernt

Reputation: 20601

You almost have it. Because myDropzone.files is an array, myDropzone.files.length will tell you if you have any selected files.

if (!myDropzone.files || !myDropzone.files.length) {
  // allow to upload file
} else {
  alert("please remove existing file");
}

I included a !myDropzone.files check because I'm not 100% sure when this property is initialized, so it may be undefined when you're trying to check its length.

Upvotes: 4

Related Questions