Drag and Drop Files using jQuery, Ajax

Drag and Drop Files using Jquery Ajax

In modern web technology, we use drag/drop system in our web page. It will be little tough if we do not use properly with JavaScript. Today I will give a clean solutions about dragging files into our html page. Its much easier than other solutions. Drag and Drop Files using jQuery, Ajax –

Step-1

Here, we will use a JS library called dropzone.js. You have to add this library in your web page head tag. Download the file from here – DropZone.js

<script src="/dropzon.js" type="text/javascript"></script>
Step-2

Create a div in you html page like the following code.

<div id="dragarea" style="width:200px;height:200px;border: 1px solid grey; padding:20px;">
<strong>File Name</strong>
<p id='filename'></p>
</div>
Step-3

For HTML and PHP, use the following JS code into the bottom of your page
Also, you have to create a function in your ACTION_URL PHP page for uploading the files in your server.

<script type="text/javascript">
$d= $("#dragarea");
$d.on('dragenter', function(ev) {
   //You can add css class for high light your drag area while you you enter your mouse
});
$d.on('dragleave', function(ev) {
   //You can remove css class for high light your drag area while you you leave your mouse
});
$d.on('dragover', function(ev) {
      ev.preventDefault();
});

$d.on('drop', function(ev) {
    ev.preventDefault();
    ev.stopPropagation();    
    if(ev.originalEvent.dataTransfer){
      if(ev.originalEvent.dataTransfer.files.length) {
        var droppedFiles = ev.originalEvent.dataTransfer.files;
        for(var i = 0; i < droppedFiles.length; i++)
        {
           var file_data = droppedFiles[i];
           $("#filename").text(file_data.name);
           var form_data = new FormData();
           form_data.append('file', file_data);
           jQuery.ajax({
               url: ACTION_URL,
               type: 'post',
               contentType: false,
               processData: false,
               data: form_data,
               dataType : "json",
               success: function(resp){
                 //Write your own code
               })
           });
        }
      }
    }
});
</script>

For WORDPRESS, first create a action in your functions.php file like the following code


add_action( 'wp_ajax_custom_file_save','custom_file_save' );
add_action( 'wp_ajax_nopriv_custom_file_save','custom_file_save' );

function custom_file_save(){
    $tmpfile = $_FILES['file'];
    $name =  $tmpfile['name'];
    $arr = explode('.',$name);
    $ext = $arr[1];
    $uploads = wp_upload_dir();	
    $filetype_info = wp_check_filetype($name);
    $file_type     = $filetype_info['type'];
    $file_ext      = $filetype_info['ext'];
    $filename 	   = wp_unique_filename( $uploads['path'], $name );
    if ( ! function_exists( 'wp_handle_upload' ) ) {
      require_once( ABSPATH . 'wp-admin/includes/file.php' );
    }
    $uploadedfile = $_FILES['file'];
    $upload_overrides = array( 'test_form' => false );
    $movefile = wp_handle_upload( $uploadedfile, $upload_overrides ); 
    if ($movefile && !isset($movefile['error'])) {		
        $attachment = array(
    			'post_mime_type' => $file_type,
    			'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
    			'post_content' => '',
    			'post_status' => 'inherit',
    			'guid' => $movefile['url']
        );
        $path = substr( $movefile['url'], strlen( $uploads['baseurl'] . '/' ) );
        $attach_id = wp_insert_attachment( $attachment, $path, 0 );
        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
        $attach_data = wp_generate_attachment_metadata( $attach_id, $movefile['file'] );
        $success = wp_update_attachment_metadata( $attach_id,  $attach_data );
        if( $success ){
           return $attach_id;
        }else{
    	   return false;
        }
     }
}

Now add the following JS Code

<script type="text/javascript">
$d= $("#dragarea");
$d.on('dragenter', function(ev) {
   //You can add css class for high light your drag area while you you enter your mouse
});
$d.on('dragleave', function(ev) {
   //You can remove css class for high light your drag area while you you leave your mouse
});
$d.on('dragover', function(ev) {
      ev.preventDefault();
});

$d.on('drop', function(ev) {
    ev.preventDefault();
    ev.stopPropagation();    
    if(ev.originalEvent.dataTransfer){
      if(ev.originalEvent.dataTransfer.files.length) {
        var droppedFiles = ev.originalEvent.dataTransfer.files;
        for(var i = 0; i < droppedFiles.length; i++)
        {
           var file_data = droppedFiles[i];
           $("#filename").text(file_data.name);
           var form_data = new FormData();
           form_data.append('file', file_data);
           form_data.append('action', 'custom_file_save');
           jQuery.ajax({
               url: 'admin-ajax.php',
               type: 'post',
               contentType: false,
               processData: false,
               data: form_data,
               dataType : "json",
               success: function(resp){
                 //Write your own code
               })
           });
        }
      }
    }
});
</script>