How to Display existing files on Server in Dropzone – PHP

Dropzone library makes it easier to implement file upload using drag and drop on the page.

After file uploading, it shows the preview of the file in the upload area.

All the thumbnails are removed when the webpage is getting refreshed.

To recreate the thumbnails after page refresh needs to send AJAX request to get all files list for adding thumbnails while initializing Dropzone.

In this tutorial, I show how you can display existing files stored on the server in the Dropzone file area with jQuery AJAX.

How to Display existing files on Server in Dropzone - PHP


Contents

  1. Download & Include
  2. HTML
  3. CSS
  4. PHP
  5. Script
  6. Demo
  7. Conclusion

1. Download & Include

Download Dropzone library from here and include in <head > section with the jQuery library.

<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- Dropzone CSS and JS -->
<link href='https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.css' type='text/css' rel='stylesheet'>
<script src='https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.js' type='text/javascript'></script>

2. HTML

Create a <form action="upload.php" class="dropzone" > for Dropzone container.

Completed Code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href="dropzone.min.css" rel="stylesheet" type="text/css">
<script src="dropzone.min.js" type="text/javascript"></script>

<div class="container" >
  <div class='content'>
    <form action="upload.php" class="dropzone" >  
    </form> 
  </div> 
</div>

3. CSS

.container{
   margin: 0 auto; 
   width: 50%;
}

.content{
   padding: 5px; 
   margin: 0 auto;
}
.content span{
   width: 250px;
}

.dz-message{
   text-align: center;
   font-size: 28px;
}

.dz-preview .dz-image img{
   width: 100% !important;
   height: 100% !important;
   object-fit: cover;
}

4. PHP

Create a new upload.php file and upload folder to store files.

If $request == 1 then store file to upload folder.

If $request == 2 then read files from upload folder and initialize $file_list Array with name, file size, and path. Return JSON response.

Completed Code

<?php
// Upload folder
$target_dir = "upload/";

$request = 1;
if(isset($_POST['request'])){
    $request = $_POST['request'];
}

// Upload file
if($request == 1){
    $target_file = $target_dir . basename($_FILES["file"]["name"]);

    $msg = "";
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir.$_FILES['file']['name'])) {
        $msg = "Successfully uploaded";
    }else{ 
        $msg = "Error while uploading";
    }
    echo $msg;
    exit;
}

// Read files from 
if($request == 2){
    $file_list = array();

    // Target folder
    $dir = $target_dir;
    if (is_dir($dir)){

        if ($dh = opendir($dir)){

           // Read files
           while (($file = readdir($dh)) !== false){

              if($file != '' && $file != '.' && $file != '..'){

                  // File path
                  $file_path = $target_dir.$file;

                  // Check its not folder
                  if(!is_dir($file_path)){

                      $size = filesize($file_path);

                      $file_list[] = array('name'=>$file,'size'=>$size,'path'=>$file_path);

                  }
              }

           }
           closedir($dh);
        }
    }

    echo json_encode($file_list);
    exit;
}

5. Script

Set Dropzone autoDiscover to false and initialize dropzone on class="dropzone".

Send AJAX POST request from init function to get all the files list. On successfully callback loop on the response and assign { name: value.name, size: value.size } in mockFile.

Use Dropzone addedfile and thumbnail functions to add the existing file to the upload area. With complete function remove the progress bar.

Completed Code

Dropzone.autoDiscover = false;
$(".dropzone").dropzone({
  init: function() { 
     myDropzone = this;
     $.ajax({
        url: 'upload.php',
        type: 'post',
        data: {request: 2},
        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);

            });

        }
     });
  }
});

6. Demo

View Demo


7. Conclusion

In the example, I read all files of the folder and display them in the Dropzone upload area. If you stored the files in the MySQL database then read it and initialize the file name, size, and path in the Array and return it from the AJAX file.

If you found this tutorial helpful then don't forget to share.