Jquery Drag and Drop Upload File Ajax
Drag and drop is a simple way to allow users to upload their files by dropping them into the container. Nowadays most websites permit uploading using both drag and drop and the file browse e.g. PushBullet, Facebook, SlideShare, etc.
I am using AJAX to save the file to the server which triggers when the file dropped on the target container.
In this tutorial, I testify how you can implement a similar blazon of feature in your project and testify a thumbnail when the file is successfully uploaded using jQuery AJAX and PHP.
           
        
Contents
- HTML
- CSS
- PHP
- jQuery
- Output
- Conclusion
i. HTML
I created a          <div class="container">          which contains the file element and a          <div class="upload-expanse" id="uploadfile">          container.
I am using this          <div>          as file uploading area where the user can drag and drop the file or open File Dialog Box by clicking on it.
Completed Code
<!doctype html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.half-dozen.0/jquery.min.js"></script> <script src="script.js" type="text/javascript"></script> </head> <body > <div class="container" > <input type="file" proper noun="file" id="file"> <!-- Drag and Drop container--> <div course="upload-area" id="uploadfile"> <h1>Elevate and Driblet file here<br/>Or<br/>Click to select file</h1> </div> </div> </trunk> </html>
2. CSS
.upload-expanse{     width: 70%;     summit: 200px;     edge: 2px solid lightgray;     border-radius: 3px;     margin: 0 auto;     margin-superlative: 100px;     text-align: heart;     overflow: auto; }  .upload-area:hover{     cursor: pointer; }  .upload-area h1{     text-marshal: centre;     font-weight: normal;     font-family: sans-serif;     line-superlative: 50px;     color: darkslategray; }  #file{     brandish: none; }  /* Thumbnail */ .thumbnail{     width: 80px;     height: 80px;     padding: 2px;     border: 2px solid lightgray;     border-radius: 3px;     float: left; }  .size{     font-size:12px; }        3. PHP
Create          upload          binder and          upload.php          file.
Use          upload          binder to shop files and too added          default.png          paradigm which uses every bit a thumbnail for non-paradigm type files.
Upload file to          upload          folder and check file is image or not. If image then assign          $location          to          $src.
Initialize          $return_arr          Array with file proper noun, size, and location.
Render          $return_arr          Array in JSON format.
Completed Code
<?php  /* Getting file proper name */ $filename = $_FILES['file']['name'];  /* Getting File size */ $filesize = $_FILES['file']['size'];  /* Location */ $location = "upload/".$filename;  $return_arr = array();  /* Upload file */ if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){     $src = "default.png";      // checking file is paradigm or not     if(is_array(getimagesize($location))){         $src = $location;     }     $return_arr = array("name" => $filename,"size" => $filesize, "src"=> $src); }  echo json_encode($return_arr);        four. jQuery
The below lawmaking stops the page from redirect when the file drop on the folio.
          // preventing page from redirecting  $("html").on("dragover", part(e) {     e.preventDefault();     east.stopPropagation();     $("h1").text("Drag here");  });   $("html").on("drop", office(e) { e.preventDefault(); e.stopPropagation(); });        This removes page default functionality.
Drag & Drop
When the file is dropped on          <div class="upload-area">          then storing the file in a variable and creating a FormData Object          fd.
Using          append()          method to store the file in FormData variable.
Passing FormData Object variable in          uploadData()          function.
From where send AJAX request and using FormData variable equally data. When the AJAX successfully callback, passing the response to          addThumbnail()          office which creates a new thumbnail and shows its information (proper noun and size).
If the uploaded file is an paradigm then testify its epitome otherwise show the default prototype.
Click
When the user clicks on the upload area and so fire the click event on the file element (id=uploadfile). Onchange upshot uploading the file and showing the thumbnail aforementioned every bit drag & driblet.
Completed Code
$(office() {      // preventing page from redirecting     $("html").on("dragover", function(e) {         e.preventDefault();         due east.stopPropagation();         $("h1").text("Drag here");     });      $("html").on("drop", function(e) { e.preventDefault(); e.stopPropagation(); });      // Drag enter     $('.upload-expanse').on('dragenter', function (east) {         east.stopPropagation();         e.preventDefault();         $("h1").text("Drop");     });      // Elevate over     $('.upload-surface area').on('dragover', function (eastward) {         e.stopPropagation();         e.preventDefault();         $("h1").text("Drop");     });      // Drib     $('.upload-area').on('drop', office (e) {         e.stopPropagation();         east.preventDefault();          $("h1").text("Upload");          var file = eastward.originalEvent.dataTransfer.files;         var fd = new FormData();          fd.append('file', file[0]);          uploadData(fd);     });      // Open up file selector on div click     $("#uploadfile").click(function(){         $("#file").click();     });      // file selected     $("#file").change(role(){         var fd = new FormData();          var files = $('#file')[0].files[0];          fd.append('file',files);          uploadData(fd);     }); });  // Sending AJAX request and upload file function uploadData(formdata){      $.ajax({         url: 'upload.php',         type: 'mail service',         data: formdata,         contentType: false,         processData: false,         dataType: 'json',         success: role(response){             addThumbnail(response);         }     }); }  // Added thumbnail office addThumbnail(information){     $("#uploadfile h1").remove();      var len = $("#uploadfile div.thumbnail").length;      var num = Number(len);     num = num + one;      var proper name = data.name;     var size = convertSize(data.size);     var src = data.src;      // Creating an thumbnail     $("#uploadfile").append('<div id="thumbnail_'+num+'" class="thumbnail"></div>');     $("#thumbnail_"+num).suspend('<img src="'+src+'" width="100%" summit="78%">');     $("#thumbnail_"+num).append('<span course="size">'+size+'<bridge>');  }  // Bytes conversion part convertSize(size) {     var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];     if (size == 0) return '0 Byte';     var i = parseInt(Math.floor(Math.log(size) / Math.log(1024)));     return Math.round(size / Math.prisoner of war(1024, i), 2) + ' ' + sizes[i]; }        5. Output
View Output
six. Conclusion
I showed how you lot implement elevate and driblet file upload functionality in your project and I didn't add whatsoever type of brake while uploading the file in PHP which yous can add equally per your requirement.
If you found this tutorial helpful then don't forget to share.
Are you want to go implementation help, or alter or extend the functionality of this script? Submit paid service asking.
Related posts:
Source: https://makitweb.com/drag-and-drop-file-upload-with-jquery-and-ajax/
0 Response to "Jquery Drag and Drop Upload File Ajax"
Post a Comment