Skip to content

Dropzone.js – 3 [Preview from upload folder]

We always want to see what we have done in the past. An user will want to see the uploaded files later.

When we reload our dropzone upload page, We can’t see the files we have uploaded before. So this time I will show you ways to see the previous uploaded files.

Extra jsvascript function to handle the dropzone initialization function::

init: function() { 
          $.ajax({
            url: 'preview.php',
            type: 'post',
            dataType: 'json',
            success: function(response){
              $.each(response, function(key,value) {
                var mockFile = { name: value.name, size: value.size };
                myDropzone.emit("addedfile", mockFile);
                myDropzone.emit("thumbnail", mockFile, value.path);
                myDropzone.emit("complete", mockFile);
              });
            }
          });
        },

So that our <script> tag will become:

  <script>
    Dropzone.autoDiscover = false;
    $( document ).ready(function() {
      var myDropzone = new Dropzone("form#demo_upload", {
        addRemoveLinks: true, 
        removedfile: function(file) {
          var name = file.name;  
          $.ajax({
            type: 'POST',
            url: 'delete.php',
            data: {name: name},
            sucess: function(data){
                console.log('success: ' + data);
            }
          });
          var _ref;
            return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
        },
        init: function() { 
          $.ajax({
            url: 'preview.php',
            type: 'post',
            dataType: 'json',
            success: function(response){
              $.each(response, function(key,value) {
                var mockFile = { name: value.name, size: value.size };
                myDropzone.emit("addedfile", mockFile);
                myDropzone.emit("thumbnail", mockFile, value.path);
                myDropzone.emit("complete", mockFile);
              });
            }
          });
        },
      });
    });
  </script>

An extra php file(preview.php) is added to get the file list to preview on init.

<?php
$file_list = array();
$dir = 'upload/';
if (is_dir($dir)){
	if ($dh = opendir($dir)){
		while (($file = readdir($dh)) !== false){
			if($file != '' && $file != '.' && $file != '..'){
				$file_path = $dir.$file;
				if(!is_dir($file_path)){
					$size = filesize($dir.$file);
					$file_list[] = array('name'=>$file,'size'=>$size,'path'=>$file_path);
				}
			}
		}
		closedir($dh);
	}
}
echo json_encode($file_list);
exit;
Leave a Reply

Your email address will not be published. Required fields are marked *