In this tutorial we will learn how to display existing files on server in Dropzone js using PHP.
How to display existing files on server in Dropzone js using PHP
If you used dropzone.js to allow documents upload like images or files, you might need to use php mysql to show already uploaded files from the database. Therefore, in this example, I created a small script to show every file which were uploaded from the upload folder. You can quickly upload files using the dropzone js library.
You just require to create two files and one "upload" folder to make it workable. Just follow this example.
Step 1 - Create Index.php File
index.php
<!DOCTYPE html>
<html>
<head>
<title>How to display existing files on server in Dropzone js using PHP</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>
.dz-preview .dz-image img{
width: 100% !important;
height: 100% !important;
object-fit: cover;
}
</style>
</head>
<body>
<div class="container" >
<h1>Dropzone display uploaded files on server in PHP</h1>
<div class='content'>
<form action="uploadFile.php" class="dropzone" >
</form>
</div>
</div>
<script type="text/javascript">
Dropzone.autoDiscover = false;
$(".dropzone").dropzone({
init: function() {
myDropzone = this;
$.ajax({
url: 'uploadFile.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>
Step 2 - Create uploadFile.php File
uploadFile.php
<?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;
}