I am going to show you, how you can create your own Drag and Drop window with the help of Dropzone and reorder your images. To achieve this task we can use a very famous Javascript Plugin Dropzone.js. To save files on the server I will use PHP as a server-side language.
Before we go you need to understand why we use Drag and Drop feature to upload images, The answer is very simple because it is very user-friendly.
If your site is user-friendly then more user visits your site and every user upload images easily and confidently.
Follow the below steps to create such a beautiful image uploader.
Create before start:
- Create a MySQL table with the name of images.
- Into your main folder Create the following folder.
- ajax
- action-z.ajax.php
- update.php
- dropzone [Download dropzone lib. Download link]
images [if you are using dropzone CDN then ignore this folder]- uploads
- Into your main folder create the following files.
- index.php
- config.php
- Database.php [It is a DB class lib Download link]
Step 1: Create Table
Create MySQL Table with the help of the below query.
CREATE TABLE `images` (
`id` int(11) NOT NULL,
`img_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`img_order` int(5) NOT NULL DEFAULT '0',
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1'
);
--
-- Indexes for table `images`
--
ALTER TABLE `images`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for table `images`
--
ALTER TABLE `images`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
If you already have a Table then change table name into config.php. at line number 25.
/*** TB DEFINE ***/
define('TB_IMG','images');
Step 2: Set config file
Create a config.php file and set up your DB with the right credentials. If you are working on a local server then use the below code.
<?php
session_start();
define('HOST', 'ofline');
error_reporting(0);
if(HOST == 'online'){
define('DB_NAME', '');
define('DB_USER', '');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('HOME_URL','https://learncodeweb/');
define("HOME_PATH",'https://learncodeweb/');
define("HOME_AJAX",HOME_URL.'ajax/');
}else{
define('DB_NAME', 'learncodeweb');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('HOME_URL','http://localhost/drop-reorder-image/');
define("HOME_PATH",'http://localhost/drop-reorder-image/');
define("HOME_AJAX",HOME_URL.'ajax/');
}
/*** TB DEFINE ***/
define('TB_IMG','images');
/*** DB INCLUDES ***/
include_once 'Database.php';
/*** DB CONNECTION ***/
$dsn = "mysql:dbname=".DB_NAME.";host=".DB_HOST."";
$pdo = '';
try {$pdo = new PDO($dsn, DB_USER, DB_PASSWORD);} catch (PDOException $e) {echo "Connection failed: " . $e->getMessage();}
/*Classes*/
$db = new Database($pdo);
?>
Step 3: Set index file
Create an index.php file and add the below code into your head tag.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
<link rel="stylesheet" href="dropzone/dropzone.css" type="text/css">
Add JavaScript files and code before the body tag close.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<script src="dropzone/dropzone.js"></script>
$(document).ready(function(){
$('.reorder').on('click',function(){
$("ul.nav").sortable({ tolerance: 'pointer' });
$('.reorder').html('Save Reordering');
$('.reorder').attr("id","updateReorder");
$('#reorder-msg').slideDown('');
$('.img-link').attr("href","javascript:;");
$('.img-link').css("cursor","move");
$("#updateReorder").click(function( e ){
if(!$("#updateReorder i").length){
$(this).html('').prepend('<i class="fa fa-spin fa-spinner"></i>');
$("ul.nav").sortable('destroy');
$("#reorder-msg").html( "Reordering Photos - This could take a moment. Please don't navigate away from this page." ).removeClass('light_box').addClass('notice notice_error');
var h = [];
$("ul.nav li").each(function() { h.push($(this).attr('id').substr(9)); });
$.ajax({
type: "POST",
url: "<?php echo HOME_AJAX; ?>update.php",
data: {ids: " " + h + ""},
success: function(data){
if(data==1 || parseInt(data)==1){
//window.location.reload();
}
}
});
return false;
}
e.preventDefault();
});
});
$(function() {
$("#myDrop").sortable({
items: '.dz-preview',
cursor: 'move',
opacity: 0.5,
containment: '#myDrop',
distance: 20,
tolerance: 'pointer',
});
$("#myDrop").disableSelection();
});
//Dropzone script
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("div#myDrop",
{
paramName: "files", // The name that will be used to transfer the file
addRemoveLinks: true,
uploadMultiple: true,
autoProcessQueue: false,
parallelUploads: 50,
maxFilesize: 5, // MB
acceptedFiles: ".png, .jpeg, .jpg, .gif",
url: "ajax/action-z.ajax.php",
});
myDropzone.on("sending", function(file, xhr, formData) {
var filenames = [];
$('.dz-preview .dz-filename').each(function() {
filenames.push($(this).find('span').text());
});
formData.append('filenames', filenames);
});
/* Add Files Script*/
myDropzone.on("success", function(file, message){
$("#msg").html(message);
setTimeout(function(){window.location.href="index.php"},200);
});
myDropzone.on("error", function (data) {
$("#msg").html('<div class="alert alert-danger">There is some thing wrong, Please try again!</div>');
});
myDropzone.on("complete", function(file) {
myDropzone.removeFile(file);
});
$("#add_file").on("click",function (){
myDropzone.processQueue();
});
});
In index body paste below code.
<div class="container">
<div class="dropzone dz-clickable" id="myDrop">
<div class="dz-default dz-message" data-dz-message="">
<span>Drop files here to upload</span>
</div>
</div>
<input type="button" id="add_file" value="Add" class="btn btn-primary mt-3">
</div>
<hr class="my-5">
<div class="container">
<a href="javascript:void(0);" class="btn btn-outline-primary reorder" id="updateReorder">Reorder Imgaes</a>
<div id="reorder-msg" class="alert alert-warning mt-3" style="display:none;">
<i class="fa fa-3x fa-exclamation-triangle float-right"></i> 1. Drag photos to reorder.<br>2. Click 'Save Reordering' when finished.
</div>
<div class="gallery">
<ul class="nav nav-pills">
<?php
//Fetch all images from database
$images = $db->getAllRecords(TB_IMG,'*','order by img_order ASC');
if(!empty($images)){
foreach($images as $row){
?>
<li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-handle mr-2 mt-2">
<div><a href="javascript:void(0);" class="img-link"><img src="uploads/<?php echo $row['img_name']; ?>" alt="" class="img-thumbnail" width="200"></a></div>
</li>
<?php
}
}
?>
</ul>
</div>
</div>
Now we just need to handle requests for upload & save images, and update reorders images.
Step 4: Set ajax action
Past below snippets into the ajax/action-z.ajax.php file.
<?php
include_once('../config.php');
if(!empty($_FILES['files'])){
$n=0;
$s=0;
$prepareNames = array();
foreach($_FILES['files']['name'] as $val)
{
$infoExt = getimagesize($_FILES['files']['tmp_name'][$n]);
$s++;
$filesName = str_replace(" ","",trim($_FILES['files']['name'][$n]));
$files = explode(".",$filesName);
$File_Ext = substr($_FILES['files']['name'][$n], strrpos($_FILES['files']['name'][$n],'.'));
if($infoExt['mime'] == 'image/gif' || $infoExt['mime'] == 'image/jpeg' || $infoExt['mime'] == 'image/png')
{
$srcPath = '../uploads/';
$fileName = $s.rand(0,999).time().$File_Ext;
$path = trim($srcPath.$fileName);
if(move_uploaded_file($_FILES['files']['tmp_name'][$n], $path))
{
$prepareNames[] .= $fileName; //need to be fixed.
$Sflag = 1; // success
}else{
$Sflag = 2; // file not move to the destination
}
}
else
{
$Sflag = 3; //extention not valid
}
$n++;
}
if($Sflag==1){
echo '{Images uploaded successfully!}';
}else if($Sflag==2){
echo '{File not move to the destination.}';
}else if($Sflag==3){
echo '{File extention not good. Try with .PNG, .JPEG, .GIF, .JPG}';
}
if(!empty($prepareNames)){
$count = 1;
foreach($prepareNames as $name){
$data = array(
'img_name'=>$name,
'img_order'=>$count++,
);
$db->insert(TB_IMG,$data);
}
}
}
?>
And for the update order of the images send a request to an update.php file. Paste below code into the ajax/update.php file.
<?php include_once '../config.php';
//get images id and generate ids array
$idArray = explode(",",$_POST['ids']);
//update images order
$count = 1;
foreach ($idArray as $id){
$data = array('img_order'=>$count);
$update = $db->update(TB_IMG,$data,array('id'=>$id));
$count ++;
}
echo '1';
?>
The working example you can download from here