Сlear dropzone thumbnail list image after uploading an image

I have code:


Dropzone.options.dpzMultipleFiles = {
    uploadMultiple: true,
    paramName: "file",
    maxFilesize: 100,
    maxFiles: 2,
    createImageThumbnails: true,
    acceptedFiles: ".png,.jpg,.jpeg",
    clickable: true,
    thumbnailWidth: 200,
    thumbnailHeight: 200,
    autoProcessQueue: false,
    init: function () {
        var submitButton = document.querySelector("#submit-all")
        dpzMultipleFiles = this;
        submitButton.addEventListener("click", function () {
            dpzMultipleFiles.processQueue();
        });



        $.ajax({
            url: 'http://localhost/admin/dropZoneUpload.php?parm=1',
            type: 'get',
            dataType: 'json',
            cache: false,
            success: function (response) {
                $.each(response, function (key, value) {
                    var mockFile = {name: value.name, size: value.size}

                    dpzMultipleFiles.emit('addedfile', mockFile)
                    dpzMultipleFiles.emit('thumbnail', mockFile, value.path)
                    dpzMultipleFiles.emit('complete', mockFile)
                })
            }
        });




        this.on('completemultiple', function (file, json) {
            //$('.sortable').sortable('enable');
        });
        // this.on("thumbnail", function(file, dataUrl) {
        //     $('.dz-image').last().find('img').attr({width: '100%', height: '100%'});
        // }),
        this.on('success', function (file, json) {
            if (file.accepted == true) {

                $('.dz-preview').remove();

                $.ajax({
                    url: 'http://localhost/psCMS2/admin/dropZoneUpload.php?parm=1',
                    type: 'get',
                    dataType: 'json',
                    cache: false,
                    success: function (response) {
                        console.log(response);
                        $.each(response, function (key, value) {
                            var mockFile = {name: value.name, size: value.size}
                            dpzMultipleFiles.emit('addedfile', mockFile)
                            dpzMultipleFiles.emit('thumbnail', mockFile, value.path)
                            dpzMultipleFiles.emit('complete', mockFile)
                        });
                    }
                });



            }
            /////////
        });

        this.on("addedfile", function (file) {
            var removeButton = Dropzone.createElement("<button> Remove file </button>");
            var _this = this;

            removeButton.addEventListener("click", function (e) {
                // Make sure the button click doesn't submit the form:
                e.preventDefault();
                e.stopPropagation();

                $.ajax({
                    url: 'http://localhost/psCMS2/admin/dropZoneUpload.php?removeFile=' + file.name,
                    dataType: 'text',
                    type: 'post',
                    cache: false,
                    data: $(this).serialize(),
                    success: function (data, textStatus, jQxhr) {
                        x = confirm('Do you want to delete this logo?');
                        if(!x)  return false;
                        //_this.removeFile();
                        dpzMultipleFiles.options.maxFiles = dpzMultipleFiles.options.maxFiles + 1;
                        console.log("kasuje " + file.name);
                        alert('http://localhost/psCMS2/admin/dropZoneUpload.php?removeFile=' + file.name);
                    }, error: function (jqXhr, textStatus, errorThrown) {
                        console.log(errorThrown);
                    }
                });
            });
            file.previewElement.appendChild(removeButton);
        });
        this.on("maxfilesexceeded", function (file) {
            this.removeFile(file);
        });
        this.on('resetFiles', function() {
            dpzMultipleFiles.removeAllFiles();
        });
        this.on('queuecomplete', function(){
            //$('.dz-preview').remove();
        });
        this.on('drop', function(){

        });
        this.on('complete', function(){
            this.removeFile(file);
        });
    }
};

I do not know why, but the above code does not clean my dropzone list before it loads new files.

I would like the code to work as follows: 1. loads files available on the server with php - works correctly 2. displays these files in the dropzone - works correctly 3. I add another file (success section) - the script uploads the file to the server - works correctly 4. The list of files should be cleared and files from the server should be loaded again - it does not work correctly.

The php script gives the correct list of files. How can I clear this list?

At the moment after uploading the photo I see the old list :frowning:

Here is full code: https://bitbucket.org/trifek/dropzone/src/master/

I’m trying to add one file and many at the same time.

In your PHP script you only move the first file to uploads/bla.jpg, and then exit:

if (!move_uploaded_file($_FILES['file']['tmp_name'][$i],  $config . "/bla.jpg")) {
    throw new RuntimeException('Failed to move uploaded file.');
} else {               
    $file_list = array();
    // etc...
    echo json_encode($file_list);
    exit;
}

You’ll probably want to move the file to $config . $_FILES['file']['name'][$i] instead, and put the JSON response part after the while loop so that all files are getting uploaded correctly.

Then in your JS, you’re fetching the list from the server for each successfully uploaded image, which results in several duplicate entries; use the successmultiple event instead:

this.on('successmultiple', function () {
  $('.dz-preview').remove()
  $.ajax({
    // etc...
  })
})

It would also be a good idea to extract this part in a dedicated function, so that you don’t have to repeat it everywhere you’re using it:

Dropzone.options.dpzMultipleFiles = {
  uploadMultiple: true,
  // etc...
  init: function () {
    var submitButton = document.querySelector('#submit-all')
    var dpzMultipleFiles = this

    var updateList = function () {
      $('.dz-preview').remove()

      $.ajax({
        url: 'dropZoneUpload.php?parm=1',
        type: 'get',
        dataType: 'json',
        cache: false,
        success: function (response) {
          $.each(response, function (key, value) {
            var mockFile = { name: value.name, size: value.size }

            dpzMultipleFiles.options.maxFiles = dpzMultipleFiles.options.maxFiles - 1
            dpzMultipleFiles.emit('addedfile', mockFile)
            dpzMultipleFiles.emit('thumbnail', mockFile, value.path)
            dpzMultipleFiles.emit('complete', mockFile)
          })
        }
      })
    }

    updateList()
    this.on('successmultiple', updateList)

    submitButton.addEventListener('click', function () {
      dpzMultipleFiles.processQueue()
    })

    // etc...
  }
}

But why clear the list in the first place?

Generally, the php file generates JSON correctly. I made such an example file only. As for the function, you are right, I will have to change it when it starts working (common function for refreshing all files)

I would like to clean the dropzone list of files after each success of the file.

Your code helped me :slight_smile: Thank you very much.

I see a small problem when I upload more than one file at a time.

Dropbox sends only one file. My current code below.

Thank you again for your help…


<script type="text/javascript">
         Dropzone.options.dpzMultipleFiles = {
             uploadMultiple: true,
             paramName: "file",
             maxFilesize: 100,
             maxFiles: 6,
             createImageThumbnails: true,
             acceptedFiles: ".png,.jpg,.jpeg",
             clickable: true,
             thumbnailWidth: 200,
             thumbnailHeight: 200,
             autoProcessQueue: false,

             init: function () {
                 var submitButton = document.querySelector("#submit-all")
                 dpzMultipleFiles = this;
                 submitButton.addEventListener("click", function () {
                     dpzMultipleFiles.processQueue();
                 });


                 $.ajax({
                     url: '{{ pageTemplate.pageHeader.baseHref}}/SystemConfiguration/ShowFiles',
                     type: 'get',
                     dataType: 'json',
                     cache: false,
                     success: function (response) {
                         $.each(response, function (key, value) {
                             dpzMultipleFiles.options.maxFiles = dpzMultipleFiles.options.maxFiles - 1;
                             var mockFile = {name: value.name, size: value.size}

                             dpzMultipleFiles.emit('addedfile', mockFile)
                             dpzMultipleFiles.emit('thumbnail', mockFile, value.path)
                             dpzMultipleFiles.emit('complete', mockFile)
                         })
                     },
                     error: function(response){
                         alert('problem z json');
                     }
                 });


                 this.on('completemultiple', function (file, json) {
                     //$('.sortable').sortable('enable');
                 });
                 this.on("thumbnail", function (file, dataUrl) {
                     $('.dz-image').last().find('img').attr({width: '100%', height: '100%'});
                 }),


                     this.on('success', function (file, json) {
                         if (file.accepted == true) {

                             $('.dz-preview').remove();
                             this.removeAllFiles;
         					//Dropzone.forElement("#dpz-multiple-files").removeAllFiles(true);



                         }
                         /////////
                     });
                 this.on('successmultiple', function () {
                     $('.dz-preview').remove()
                     $.ajax({
                         url: '{{ pageTemplate.pageHeader.baseHref}}/SystemConfiguration/ShowFiles',
                         type: 'get',
                         dataType: 'json',
                         cache: false,
                         success: function (response) {
                             $.each(response, function (key, value) {
                                 var mockFile = {name: value.name, size: value.size}
                                 dpzMultipleFiles.emit('addedfile', mockFile)
                                 dpzMultipleFiles.emit('thumbnail', mockFile, value.path)
                                 dpzMultipleFiles.emit('complete', mockFile)
                             });
                         }
                         ,
                         error: function(response){
                             alert('problem z json');
                         }
                     });
                 })
                 this.on("addedfile", function (file) {
                     var removeButton = Dropzone.createElement("<button> Remove file </button>");

                     var _this = this;

                     removeButton.addEventListener("click", function (e) {
                         // Make sure the button click doesn't submit the form:
                         e.preventDefault();
                         e.stopPropagation();

                         $.ajax({
                             url: '{{ pageTemplate.pageHeader.baseHref}}/SystemConfiguration/RemoveFile?removeFile=' + file.name,
                             dataType: 'text',
                             type: 'post',
                             cache: false,
                             data: $(this).serialize(),
                             success: function (data, textStatus, jQxhr) {
                                 x = confirm('Do you want to delete this logo?');
                                 if (!x) return false;
                                 //_this.removeFile();
                                 dpzMultipleFiles.options.maxFiles = dpzMultipleFiles.options.maxFiles + 1;
                                 console.log("kasuje " + file.name);
                                 alert('{{ pageTemplate.pageHeader.baseHref}}/SystemConfiguration/RemoveFile/?removeFile=' + file.name);
                             }, error: function (jqXhr, textStatus, errorThrown) {
                                 console.log(errorThrown);
                                 alert('problem z json');
                             }
                         });
                     });
                     file.previewElement.appendChild(removeButton);
                 });
                 this.on("maxfilesexceeded", function (file) {
                     this.removeFile(file);
                 });
                 this.on('resetFiles', function () {
                     dpzMultipleFiles.removeAllFiles();
                 });
                 this.on('queuecomplete', function () {
                     //$('.dz-preview').remove();
                 });
                 this.on('drop', function () {

                 });
                 this.on('complete', function () {
                 });
             }
         };


         $(function () {
             $(".dropzone").sortable({
                 items: '.dz-preview',
                 cursor: 'move',
                 opacity: 0.5,
                 containment: '.dropzone',
                 distance: 20,
                 tolerance: 'pointer',
                 update: function (event, ui) {
                     //console.log(ui);

                     //alert('PRZENOSZE');

                     $(".dz-filename span").each(function (index) {
                         console.log(index + ": " + $(this).text());
                     });
                 }
             });
         });
      </script>

Dropzone sends all files correctly – again, it’s your PHP script that exits after the first file got moved to the uploads folder.

Hmmm… I have now (updated) to upload this function.

do you see any error in this code?

no matter if I send 2.3 or 4 files at once - the script always indicates that there are 2

public function uploadFile1(array $filesArray, string $destinationFilePath, bool $fileValidation = true, string $fileType, int $category = 0, array $acceptFormat)
    {


        // $i = 0;
        //while ($i <= count($files['name'][$i])) {
        for ($i = 0; $i <= count($filesArray['name']) + 1; $i++) {
            foreach ($filesArray as $files) {

                //// SKASOWAC
                $file = 'txt' . $i . '.txt';
                $fp = fopen($file, 'w');
                fwrite($fp, 'Ilosc: ' . count($filesArray['name']) . ' wyniki:' . $filesArray['name'][$i] . ''. $filesArray['error'][$i] . ''. $filesArray['tmp_name'][$i] . "-----\n\r");
                file_put_contents($file, print_r($filesArray, true), FILE_APPEND);
                fclose($fp);
                ///////////////


                try {
                    if (
                        !isset($filesArray['error'][$i]) ||
                        is_array($filesArray['error'][$i])
                    ) {
                        //   throw new RuntimeException('Invalid parameters.');
                    }

                    switch ($filesArray['error'][$i]) {
                        case UPLOAD_ERR_OK:
                            break;
                        case UPLOAD_ERR_NO_FILE:
                            throw new RuntimeException('No file sent.');
                        case UPLOAD_ERR_INI_SIZE:
                        case UPLOAD_ERR_FORM_SIZE:
                            throw new RuntimeException('Exceeded filesize limit.');
                        default:
                            throw new RuntimeException('Unknown errors.');
                    }

                    if ($filesArray['size'] > 1000000000) {
                        // throw new RuntimeException('Exceeded filesize limit.');
                    }

                    $ext = strtolower(pathinfo($filesArray['name'][$i], PATHINFO_EXTENSION));
                    if (!in_array($ext, array_keys($acceptFormat)) && $fileValidation == true) {
                        // throw new RuntimeException('Invalid file format.');
                    }

                    $mime = mime_content_type($filesArray['tmp_name'][$i]);
                    if (!in_array($mime, array_values($acceptFormat)) && $fileValidation == true) {
                        // throw new RuntimeException('Invalid mime format.');
                    }

                    require_once $this->_config->function_path . "RandomFileName.php";
                    $pathTmpName = pathinfo($filesArray['name'][$i]);
                    $fileExtension = strtolower($pathTmpName['extension']);

                    $randomName = randomFileName(60);

                    $newFileName = $randomName . "." . $fileExtension;

                    if (!file_exists($destinationFilePath)) {
                        mkdir($destinationFilePath, 0777);
                    }
                    if (!file_exists($destinationFilePath . "/thumbs")) {
                        mkdir($destinationFilePath . "/thumbs", 0777);
                    }

                    if (!move_uploaded_file($filesArray['tmp_name'][$i], $destinationFilePath . "/" . $newFileName)) {
                        //throw new RuntimeException('Failed to move uploaded file.');
                    } else {

                        //return $newFileName;
                    }

                } catch (RuntimeException $e) {
                    //echo $e->getMessage();
                }
                //$i++;
            }
        }
        //return "";
    }

You’re returning from that function after the first successful upload, so no further files will be processed:

if (!move_uploaded_file($files['tmp_name'][$i], $destinationFilePath . "/" . $newFileName)) {
    throw new RuntimeException('Failed to move uploaded file.');
} else {
    $this->saveFileNameInDB($destinationFilePath, $newFileName, $fileType, $category);
    return $newFileName; // <- here
}

This is correct solution. Thank you very much for help:


public function uploadFile(array $filesArray, string $destinationFilePath, bool $fileValidation = true, string $fileType, int $category = 0, array $acceptFormat):array
    {
        require_once $this->_config->function_path . "RandomFileName.php";
        $result = array();
        foreach($filesArray["file"]["tmp_name"] as $key=>$tmp_name)
        {
            $temp = array();
            $ext = strtolower(pathinfo($filesArray["file"]["name"][$key], PATHINFO_EXTENSION));
            if (!in_array($ext, array_keys($acceptFormat)) && $fileValidation == true) {
                $temp['newFileName'] = $filesArray["file"]["name"][$key];
                $temp['error'] = 'Invalid file format.';
                $temp['newFileNamePath'] = '';
            }else if ($filesArray["file"]["size"][$key] > 10000000000)
            {
                $temp['newFileName'] = $filesArray["file"]["name"][$key];
                $temp['error'] = 'Exceeded filesize limit.';
                $temp['newFileNamePath'] = '';
            }
            else if(is_uploaded_file($filesArray["file"]["tmp_name"][$key])){
                $randomName = randomFileName(60);
                $newFileName = $randomName . "." . $ext;

                if (!file_exists($destinationFilePath)) {
                    mkdir($destinationFilePath, 0777);
                }

                if (!file_exists($destinationFilePath."/thumbs")) {
                    mkdir($destinationFilePath."/thumbs", 0777);
                }

                if(move_uploaded_file($filesArray["file"]["tmp_name"][$key] , $destinationFilePath."/".$newFileName))
                {
                    $temp['newFileName']=$newFileName;
                    $temp['error'] = '';
                    $temp['newFileNamePath'] = $destinationFilePath;
                    $this->saveFileNameInDB($destinationFilePath, $newFileName, $fileType, $category);
                }else{
                    $temp['newFileName'] = $filesArray["file"]["name"][$key];
                    $temp['error'] = 'Failed to move uploaded file.';
                    $temp['newFileNamePath'] = '';
                }
            }
            array_push($result,$temp);
        }
        return $result;
    }

Glad I could help! :-)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.