Drag And Drop File Upload jquery and HTML5 the Easy Way

Today, We want to share with you drag and drop file upload jquery.In this post we will show you html5 drag and drop file upload jquery, hear for how to insert image in database using php? we will give you demo and example for implement.In this post, we will learn about 5 Ways To Bootstrap File Upload with an example.

drag and drop file upload jquery

There are the Following The simple About multiple image upload jquery Full Information With Example and source code.


As I will cover this Post with live Working example to develop Drag and drop file upload with submit button, so the upload image using jquery is used for this example is following below.

Bootstrap dropzone is a jQuery Best plugin used to create a highly customizable drag and drop file upload jquery for file uploading with a great progress bar.

drag and drop file upload jquery and AJAX

In drag and drop file upload jquery example, We have explained step by step how to implement html5 drag and drop file upload jquery API.

using Drag and drop multiple file upload using jQuery, Ajax, and PHP

index.php

<!DOCTYPE html>
<html>

<head>
  <title>Drag and drop Multiple file upload using Ajax JQuery PHP - pakainfo</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
  h3 {
    line-height: 30px;
    text-align: center;
  }

  #drag_and_drop {
    height: 200px;
    border: 2px dashed #ccc;
    line-height: 200px;
    text-align: center;
    font-size: 20px;
    background: #f9f9f9;
    margin-bottom: 15px;
  }

  .drag_over {
    color: #000;
    border-color: #000;
  }

  .thumbnail {
    width: 100px;
    height: 100px;
    padding: 2px;
    margin: 2px;
    border: 2px solid lightgray;
    border-radius: 3px;
    float: left;
  }

  #drag_store_img {
    display: none;
  }
</style>
</head>

<body>
  <div class="container">
    <h3>Drag and drop multiple file upload using jQuery, Ajax and PHP - <a href="https://www.pakainfo.com" target="_blank" rel="noopener noreferrer">pakainfo</a></h3><br />
    <div id="drag_and_drop">
      Drag and Drop Files Here
    </div>
    <div id="uploaded_file"></div>
  </div>

  <script>
  $(document).ready(function () {
    $("html").on("dragover", function (e) {
      e.preventDefault();
      e.stopPropagation();
    });

    $("html").on("drop", function (e) {
      e.preventDefault();
      e.stopPropagation();
    });

    $('#drag_and_drop').on('dragover', function () {
      $(this).addClass('drag_over');
      return false;
    });

    $('#drag_and_drop').on('dragleave', function () {
      $(this).removeClass('drag_over');
      return false;
    });

    $('#drag_and_drop').on('drop', function (e) {
      e.preventDefault();
      $(this).removeClass('drag_over');
      var formData = new FormData();
      var files = e.originalEvent.dataTransfer.files;
      for (var i = 0; i < files.length; i++) {
        formData.append('file[]', files[i]);
      }
      uploadFormData(formData);
    });

    function uploadFormData(form_data) {
      $.ajax({
        url: "img_fl_store.php",
        method: "POST",
        data: form_data,
        contentType: false,
        cache: false,
        processData: false,
        success: function (data) {
          $('#uploaded_file').append(data);
        }
      });
    }
  });
</script>

</body>

</html>

First of all, we have to create a products table in the database.

Write PHP code to upload files

Create database

CREATE TABLE products(
id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
file_name varchar(255) NOT NULL,
upload_time varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

db_config.php

<?php
	$dbhost = "localhost";
	$dbuser = "root";
	$dbpass = "";
	$db = "example";
	$con = mysqli_connect($dbhost, $dbuser, $dbpass , $db) or die($con);
?>

img_fl_store.php

<?php
// Include the database connection file
include('db_config.php');
$fileData = '';
if(isset($_FILES['file']['name'][0]))
{
  foreach($_FILES['file']['name'] as $keys => $values)
  {
    $fileName = $_FILES['file']['name'][$keys];
    if(move_uploaded_file($_FILES['file']['tmp_name'][$keys], 'uploads/' . $values))
    {
      $fileData .= '<img src="uploads/'.$values.'" class="thumbnail" />';
      $query = "INSERT INTO products (file_name, upload_time)VALUES('".$fileName."','".date("Y-m-d H:i:s")."')";
      mysqli_query($con, $query);
    }
  }
}
echo $fileData;
?>

drag and drop file upload jquery
drag and drop file upload jquery

html5 drag and drop file upload jquery

simple use Drag And Drop File Upload Plugin For Bootstrap – dropzone.

Read Also:  country state city drop down list using JavaScript

HTML5 File Uploads with jQuery

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>HTML5 File Drag and Drop Upload with jQuery and PHP | pakainfo Demo</title>
        <link rel="stylesheet" href="assets/css/styles.css" />
         <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    </head>

    <body>

        <header>
            <h2>HTML5 File Upload with jQuery and PHP - www.pakainfo.com</h2>
        </header>

        <div id="uploadfile">
            <span class="message">Drop images here to upload. <br /><i>(they will only be visible to you)</i></span>
        </div>

        <div class="preview done">

		    <span class="boxfileHld">
		        <img src="" />
		        <span class="uploaded"></span>
		    </span>

		    <div class="progressHolder">
		        <div class="progress"></div>
		    </div>

		</div>

        <!-- Including The jQuery Library -->
        <script src="http://code.jquery.com/jquery-1.6.3.min.js"></script>

        <!-- Including the HTML5 Uploader plugin -->
        <script src="assets/js/jquery.filedrop.js"></script>

        <!-- The main script file -->
        <script src="assets/js/script.js"></script>

    </body>
</html>

The jQuery Code

assets/js/script.js

var carddata = '<div class="preview">'+
                        '<span class="boxfileHld">'+
                            '<img />'+
                            '<span class="uploaded"></span>'+
                        '</span>'+
                        '<div class="progressHolder">'+
                            '<div class="progress"></div>'+
                        '</div>'+
                    '</div>'; 

    function createImage(file){

        var preview = $(carddata),
            image = $('img', preview);

        var reader = new FileReader();

        image.width = 100;
        image.height = 100;

        reader.onload = function(e){

            image.attr('src',e.target.result);
        };

        // Reading the file as a DataURL. When finished,
        // this will trigger the onload function above:
        reader.readAsDataURL(file);

        message.hide();
        preview.appendTo(uploadfile);

        // Associating a preview container
        // with the file, using jQuery's $.data():

        $.data(file,preview);
    }

assets/js/script.js

$(function(){

    var uploadfile = $('#uploadfile'),
        message = $('.message', uploadfile);

    uploadfile.filedrop({
        // The name of the $_FILES entry:
        paramname:'pic',

        maxfiles: 5,
        maxfilesize: 2, // in mb
        url: 'post_file.php',

        uploadFinished:function(i,file,response){
            $.data(file).addClass('done');
            // response is the JSON object that post_file.php returns
        },

        error: function(err, file) {
            switch(err) {
                case 'BrowserNotSupported':
                    showMessage('Your browser does not support HTML5 file uploads!');
                    break;
                case 'TooManyFiles':
                    alert('Too many files! Please select 5 at most!');
                    break;
                case 'FileTooLarge':
                    alert(file.name+' is too large! Please upload files up to 2mb.');
                    break;
                default:
                    break;
            }
        },

        // Called before each upload is started
        beforeEach: function(file){
            if(!file.type.match(/^image\//)){
                alert('Only images are allowed!');

                // Returning false will cause the
                // file to be rejected
                return false;
            }
        },

        uploadStarted:function(i, file, len){
            createImage(file);
        },

        progressUpdated: function(i, file, progress) {
            $.data(file).find('.progress').width(progress);
        }

    });

    var carddata = '...'; 

    function createImage(file){
        // ... see above ...
    }

    function showMessage(msg){
        message.html(msg);
    }

});

The PHP Code

post_file.php

$example_mode = false;
$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');

if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
    exit_status('Error! Wrong HTTP method!');
}

if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){

    $pic = $_FILES['pic'];

    if(!in_array(get_extension($pic['name']),$allowed_ext)){
        exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
    }   

    if($example_mode){

        $line = implode('       ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
        file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);

        exit_status('Uploads are ignored in example mode.');
    }

    // Move the uploaded file from the temporary
    // directory to the uploads folder:

    if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
        exit_status('File was uploaded successfuly!');
    }

}

exit_status('Something went wrong with your upload!');

function exit_status($str){
    echo json_encode(array('status'=>$str));
    exit;
}

function get_extension($file_name){
    $ext = explode('.', $file_name);
    $ext = array_pop($ext);
    return strtolower($ext);
}

The CSS Styles

assets/css/styles.css

#uploadfile{
    background:url('../img/background_tile_3.jpg');

    border-radius:3px;
    position: relative;
    margin:80px auto 90px;
    min-height: 290px;
    overflow: hidden;
    padding-bottom: 40px;
    width: 990px;

    box-shadow:0 0 4px rgba(0,0,0,0.3) inset,0 -3px 2px rgba(0,0,0,0.1);
}

#uploadfile .message{
    font-size: 11px;
    text-align: center;
    padding-top:160px;
    display: block;
}

#uploadfile .message i{
    color:#ccc;
    font-size:10px;
}

#uploadfile:before{
    border-radius:3px 3px 0 0;
}

#uploadfile .preview{
    width:245px;
    height: 215px;
    float:left;
    margin: 55px 0 0 60px;
    position: relative;
    text-align: center;
}

#uploadfile .preview img{
    max-width: 240px;
    max-height:180px;
    border:3px solid #fff;
    display: block;

    box-shadow:0 0 2px #000;
}

#uploadfile .boxfileHld{
    display: inline-block;
    position:relative;
}

#uploadfile .uploaded{
    position: absolute;
    top:0;
    left:0;
    height:100%;
    width:100%;
    background: url('../img/done.png') no-repeat center center rgba(255,255,255,0.5);
    display: none;
}

#uploadfile .preview.done .uploaded{
    display: block;
}

#uploadfile .progressHolder{
    position: absolute;
    background-color:#252f38;
    height:12px;
    width:100%;
    left:0;
    bottom: 0;

    box-shadow:0 0 2px #000;
}

#uploadfile .progress{
    background-color:#2586d0;
    position: absolute;
    height:100%;
    left:0;
    width:0;

    box-shadow: 0 0 1px rgba(255, 255, 255, 0.4) inset;

    -moz-transition:0.25s;
    -webkit-transition:0.25s;
    -o-transition:0.25s;
    transition:0.25s;
}

#uploadfile .preview.done .progress{
    width:100% !important;
}

How to Upload & Display Image Using jQuery AJAX PHP and MySQL?

upload image using jquery

Read Also:  jQuery Ajax change dropdown list value

In this section I will learn how to upload & display image using jQuery AJAX in PHP MySQL. as well as step by step uploading images using the jquery AJAX function is simply and easy way step by step to implement on your web application.

Create HTML Image Upload Form

index.php

<!Doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>How to Upload & Display Image Using jQuery AJAX PHP and MySQL</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
  <body style="margin-top:50px;background:#f2f2f2">
    <div class="container">
      <h2 style="text-align:center;">How to Upload & Display Image Using jQuery AJAX PHP and MySQL</h2>
        <div class="row">
         <div class="col-md-4"></div>  
          <div class="col-md-4" style="margin-top:20px;margin-bottom:20px;">

          <div class="alert alert-success alert-dismissible success" style="display: none;">
            <button type="button" class="close" data-dismiss="alert">×</button>
            <span class="success-message">File uploaded successfully</span>  
          </div>
          <div class="alert alert-danger alert-dismissible danger" style="display: none;">
            <button type="button" class="close" data-dismiss="alert">×</button>
            <span class="danger-message">This type of image is not allow</span>  
          </div>

          <form id="submitForm">
            <div class="form-group">
              <label for="file">Select File</label>
              <input type="file" class="form-control" name="file" id="image" required="">
            </div>
            <div class="form-group">
              <button type="submit" class="btn btn-success btn btn-block">Upload</button>
            </div>  
          </form>
        </div>
      </div>
      <div class="row">
      <div class="col-md-4"></div>  
        <div class="card col-md-4" id="preview" style="display: none;">
          <div class="card-body" id="imageView">
                   
          </div>
        </div>    
      </div>
    </div>
  </body>
</html>

Upload Image to use jQuery AJAX

add jQuery ajax file upload

<script type="text/javascript">
  $(document).ready(function(){
      $("#submitForm").on("submit", function(e){
        e.preventDefault();
        var formData = new FormData(this);
        $.ajax({
          url  : "upload.php",
          type : "POST",
          cache:false,
          data :formData,
          contentType : false, // you can also use multipart/form-data replace of false
          processData: false,
          success:function(response){
            $("#preview").show();
            $("#imageView").html(response);
            $("#image").val('');
          }
        });
      });
  });
</script>

Create PHP file to upload and show Image

upload.php
upload file using move_uploaded_file function in php

<?php
	
	if (!empty($_FILES['file']['name'])) {

		$fileName = $_FILES['file']['name'];
		
		$fileExt = explode('.', $fileName);
		$fileActExt = strtolower(end($fileExt));
		$allowImg = array('png','jpeg','jpg');
		$fileNew = rand() . "." . $fileActExt;
		$filePath = 'uploads/'.$fileNew; 

		if (in_array($fileActExt, $allowImg)) {
		    if ($_FILES['file']['size'] > 0  && $_FILES['file']['error']==0) {  
			if (move_uploaded_file($_FILES['file']['tmp_name'], $filePath)) {
		    	    echo '<img src="'.$filePath.'" style="width:320px;height:300px;"/>';
			}else{
			    echo "File is not uploaded try again";
			}	
		    }else{
		    	    echo "Unable to upload physical file";
		    }
		}else{	
		    echo "This type of image is not allow";
		}
	}

?>

multiple image upload jquery

in this part you can learn to “How to upload multiple images through ajax jquery” Example.

Read Also:  Laravel 6 CSRF Protection Token Examples

Steps 1: Create Database Table

CREATE TABLE IF NOT EXISTS `uploads` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`file_name` varchar(255) NOT NULL,
`upload_time` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;

Steps 2: Create Database Connection

db_connect.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "phpzag_demos";
$conn = mysqli_connect($servername, $username, $password, $dbname);
?>

Steps 3: Include jQuery Files

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="scripts/jquery.form.js"></script>
<script type="text/javascript" src="scripts/upload.js"></script>
<link type="text/css" rel="stylesheet" href="style.css" />

Step 4: Create File Upload Form HTML

index.php

<div class="container">
	<h2>Upload Multiple Images using jQuery, Ajax and PHP</h2>
	<br>
	<br>	
	<form method="post" name="upload_form" id="upload_form" 
enctype="multipart/form-data" action="upload.php">   
    <label>Choose Multiple Images to Upload</label>
	<br>
	<br>
    <input type="file" name="multiple_img_all[]" id="image_file" multiple >
    <div class="img_fl_storeing hidden">
        <label> </label>
        <img src="uploading.gif" alt="Uploading......"/>
    </div>
	</form>
	<div id="uploaded_images_preview"></div>
</div>

Steps 5: Handle Form Submit with jQuery Form

upload.js

$(document).ready(function(){
    $('#image_file').on('change',function(){
        $('#upload_form').ajaxForm({           
            target:'#uploaded_images_preview',
            beforeSubmit:function(e){
                $('.img_fl_storeing').show();
            },
            success:function(e){
                $('.img_fl_storeing').hide();
            },
            error:function(e){
            }
        }).submit();
    });
});

Steps 6: Handle Multiple Image Upload and Insert using PHP

upload.php

<div class="row">
	<div class="gallery">
		<?php
		if(!empty($uploaded_images)){ 
			foreach($uploaded_images as $image){ ?>
			<ul>
				<li >
					<img class="images" 
src="<?php echo $image; ?>" alt="">
				</li>
			</ul>
		<?php }	}?>
	</div>
</div>
<?php
$uploaded_images = array();
foreach($_FILES['multiple_img_all']['name'] as $key=>$val){        
	$upload_dir = "uploads/";
	$drag_store_img = $upload_dir.$_FILES['multiple_img_all']['name'][$key];
	$filename = $_FILES['multiple_img_all']['name'][$key];
	if(move_uploaded_file($_FILES['multiple_img_all']['tmp_name'][$key],$drag_store_img)){
		$uploaded_images[] = $drag_store_img;
		$insert_sql = "INSERT INTO uploads(id, file_name, upload_time) 
			VALUES('', '".$filename."', '".time()."')";
		mysqli_query($conn, $insert_sql) or die("database error: ". mysqli_error($conn));
	}
}
?>

Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Upload Multiple Images using jQuery, Ajax and PHP.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.