In this tutorial, we will show you how to display existing files on the server when using DropzoneJs and PHP. This tutorial is based on How to build a file upload form using DropzoneJs and PHP. Make sure you have read it before proceeding to content in this tutorial.
In previous tutorial. We have already set up a proper working DropzoneJs upload form. There is no additional file needed for this tutorial. What we need to do is to make some modifications to file below:
Let us get started!
In previous tutorial. All upload.php does is to store uploaded files to the server directory "uploads". So we need to add a piece of code to retrieve stored files' information (name and size), and return it in JSON format.
Copy the content below to upload.php. Line 16 to 33 is what we added. And we will explain it in details.
<?php
$ds = DIRECTORY_SEPARATOR;
$storeFolder = 'uploads';
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
} else {
$result = array();
$files = scandir($storeFolder); //1
if ( false!==$files ) {
foreach ( $files as $file ) {
if ( '.'!=$file && '..'!=$file) { //2
$obj['name'] = $file;
$obj['size'] = filesize($storeFolder.$ds.$file);
$result[] = $obj;
}
}
}
header('Content-type: text/json'); //3
header('Content-type: application/json');
echo json_encode($result);
}
?>
As you can see, we added an additional "else" statement, when the HTTP Request does not contain files. This is used to detect already stored files on server for our need. Let us see what they actually do.
Copy content below to index.php. We will go through modifications individually.
<html>
<head>
<link href="css/dropzone.css" type="text/css" rel="stylesheet" />
<!-- 1 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="dropzone.min.js"></script>
<script>
<!-- 3 -->
Dropzone.options.myDropzone = {
init: function() {
thisDropzone = this;
<!-- 4 -->
$.get('upload.php', function(data) {
<!-- 5 -->
$.each(data, function(key,value){
var mockFile = { name: value.name, size: value.size };
thisDropzone.options.addedfile.call(thisDropzone, mockFile);
thisDropzone.options.thumbnail.call(thisDropzone, mockFile, "uploads/"+value.name);
});
});
}
};
</script>
</head>
<body>
<!-- 2 -->
<form action="upload.php" class="dropzone" id="my-dropzone"></form>
</body>
</html>
If you have done it successfully. Now go and upload some images and reload the upload page. Already uploaded files should auto display in Dropzone area.
Hopefully this simple tutorial helped you with your development. If you like our post, please follow us on Twitter and help spread the word. We need your support to continue. If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.