How to Display Existing Files on Server in Dropzone JS ?

12-May-2020

.

Admin

Hi Dev,

In this blog, I will teach you how to display existing files or image on server in dropzone js. I will learn to show you existing image on dropzone js in php.

You can simply and easily to upload files or image on server using dropzone js. if you used dropzone js for uploading files and image then you might be need to show existing files or image from database using php mysql.

You will create just two files and one "upload" folder to make it done this example ,so just follow bellow example.

Create Index.php File


<!DOCTYPE html>

<html>

<head>

<title>How to Display Existing Files on Server in Dropzone JS - NiceSnippets.com</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<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>

<style type="text/css">

.dz-preview .dz-image img{

width: 100% !important;

height: 100% !important;

object-fit: cover;

}

</style>

</head>

<body>

<div class="container" >

<h1>How to Display Existing Files on Server in Dropzone JS - NiceSnippets.com</h1>

<div class='content'>

<form action="upload.php" class="dropzone" >

</form>

</div>

</div>

<script type="text/javascript">

Dropzone.autoDiscover = false;

$(".dropzone").dropzone({

init: function() {

myDropzone = this;

$.ajax({

url: 'upload.php',

type: 'post',

data: {request: 'fetch'},

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>

</body>

</html>

Create upload.php File

<?php

/* Upload directory*/

$targetDir = "upload/";

$request = "upload";

if(isset($_POST['request'])){

$request = $_POST['request'];

}

/* Upload file */

if($request == "upload"){

$msg = "";

if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetDir.$_FILES['file']['name'])) {

$msg = "Successfully uploaded";

}else{

$msg = "Error while uploading";

}

echo $msg;

exit;

}

/* Read files from */

if($request == 'fetch'){

$fileList = [];

$dir = $targetDir;

if (is_dir($dir)){

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

while (($file = readdir($dh)) !== false){

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

$file_path = $targetDir.$file;

if(!is_dir($file_path)){

$size = filesize($file_path);

$fileList[] = ['name'=>$file, 'size'=>$size, 'path'=>$file_path];

}

}

}

closedir($dh);

}

}

echo json_encode($fileList);

exit;

}

It will help you...

#PHP

#Laravel 7