Showing posts with label file upload. Show all posts
Showing posts with label file upload. Show all posts

Tuesday, December 27, 2022

wordpress crud with file upload ajax frontend

Hello

Today I saw you crud  ajax operation with file upload in front side of wordpress website. Create a plugin for it, make shortcode and use it in wordpress page/post. 

Make file structure like this.




FILE : ajax-front.php

<?php

/*

Plugin Name: AJAX FRONT CRUD with media upload

Plugin URI: #

Description: A simple plugin that allows you to perform Create (INSERT), Read (SELECT), Update, Delete, File upload operations with ajax in FRONT SIDE.

Version: 1.0.0

Author: Chirag

Author URI: #

License: GPL2

*/

defined( 'ABSPATH' ) || exit;


/**

 * DEFINE PATHS

 */

global $wpdb;

define( 'MY_FRONT_CRUDURL', plugin_dir_url( __FILE__ ) );

define( 'MY_FRONT_CRUDPATH', plugin_dir_path( __FILE__ ));


//load css and js

function frontend_cssjs() {

  wp_register_style( 'customcss', MY_FRONT_CRUDURL.'/css/style.css', false, '1.0.0' );

  wp_enqueue_style( 'customcss' );


  wp_register_style('prefix_bootstrapcss', 'https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css');

  wp_enqueue_style('prefix_bootstrapcss');

  wp_register_script('prefix_bootstrapjs', 'https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js');

  wp_enqueue_script('prefix_bootstrapjs');


  wp_enqueue_script( 'my_jquery', MY_FRONT_CRUDURL. 'js/jQuery.min.js' );

  wp_enqueue_script( 'myjs', MY_FRONT_CRUDURL. 'js/crud.js' );

  wp_localize_script( 'myjs', 'ajax_var', array( 'ajaxurl' => admin_url('admin-ajax.php') ));


// Enqueue WordPress media scripts

    //wp_enqueue_media();

    // Enqueue custom script that will interact with wp.media

    //wp_enqueue_script( 'myprefix_script', plugins_url( '/js/myscript.js' , __FILE__ ), array('jquery'), '0.1' );

}

add_action('wp_enqueue_scripts','frontend_cssjs');




function pwwp_enqueue_my_scripts() {

    // jQuery is stated as a dependancy of bootstrap-js - it will be loaded by WordPress before the BS scripts 

    wp_enqueue_script( 'bootstrap-js', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js', array('jquery'), true); // all the bootstrap javascript goodness

}

add_action('wp_enqueue_scripts', 'pwwp_enqueue_my_scripts');


function pwwp_enqueue_my_styles() {

    wp_enqueue_style( 'bootstrap', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' );


    // this will add the stylesheet from it's default theme location if your theme doesn't already

    //wp_enqueue_style( 'my-style', get_template_directory_uri() . '/style.css');

}

add_action('wp_enqueue_scripts', 'pwwp_enqueue_my_styles');





//activation hook

register_activation_hook( __FILE__, 'createfrontcrud');

function createfrontcrud() {

  global $wpdb;

  $charset_collate = $wpdb->get_charset_collate();

  $table_name = $wpdb->prefix . 'crudfront';

  $sql = "CREATE TABLE `$table_name` (

    `user_id` int(11) NOT NULL AUTO_INCREMENT,

    `name` varchar(220) DEFAULT NULL,

    `email` varchar(220) DEFAULT NULL,

    `filepath` varchar(256) DEFAULT NULL,

    PRIMARY KEY(user_id)

    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

    ";

  if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

    dbDelta($sql);

  }

}


require_once(MY_FRONT_CRUDPATH.'/ajax_action.php');



//[frontend_crud]

//add_shortcode('frontendcrudnew','front_crud_file');

function register_shortcodes(){

   add_shortcode('frontendcrudnew', 'front_crud_file');

}

add_action( 'init', 'register_shortcodes');


//display data

function front_crud_file(){ 

html_addbuton();

html_display_data();

edit_data();

}



function html_addbuton(){ ?>

<!-- Button trigger modal -->

<div class="">

  <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">

    Insert Data

  </button>

  <div id="msg"></div>

</div>

<!-- Modal -->

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

  <div class="modal-dialog" role="document">

    <div class="modal-content">

      <div class="modal-header">

        <h4 class="modal-title" id="myModalLabel">Add page for under construction</h4>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

      </div>

      <div class="modal-body">

          <div class="wqsubmit_message"></div>


          <form name="insertform" id="insertform" enctype="multipart/form-data">

            <table>

              <tbody>

                <tr>

                  <td><input type="text" value="AUTO_GENERATED" disabled></td>

                </tr>

                <tr>

                  <td><input type="text" id="newname" name="newname" placeholder="Name Here"></td>

                </tr>

                <tr>

                  <td><input type="text" id="newemail" name="newemail" placeholder="Email ID Here"></td>

                </tr>

                <tr>

<td>

<input type="file" name="file1" id="file1">

</td>

                </tr>

              </tbody>

            </table>

          

        </form>


      </div>

      <div class="modal-footer">

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        <button type="button" class="btn btn-primary" id="savedata" name="savedata" >Insert Data</button>

        <!-- <div><input type="submit" class="btn btn-primary wqsubmit_button" id="wqadd" value="Add" /></div> -->

        

        <!-- <input type="submit" id="savedata" name="savedata" class="button button-primary" value="Save Data"> -->

      </div>

    </div>

  </div>

</div>

<!-- END Modal -->

<?php

}


function html_display_data(){

?>

<div class="wrap">

    <h2>DATA FRONTEND ALL</h2>

    <table class="wp-list-table widefat striped">

      <thead>

        <tr>

          <th width="5%">User ID</th>

          <th width="20%">Name</th>

          <th width="20%">Email Address</th>

          <th width="45%">Image</th>

          <th width="10%">Actions</th>

        </tr>

      </thead>

      <tbody>

        

        <?php

        global $wpdb;

        $table_name = $wpdb->prefix . 'crudfront';

          $result = $wpdb->get_results("SELECT * FROM $table_name");

          //print_r($result);

          $rowcount = count((array)$result);

          //echo "c:".$rowcount;

          //echo $last_query = $wpdb->last_query;

          if ($rowcount == 0) {

            echo "<tr> <td colspan='5'>No data found! </td></tr>";

          } else { 

            foreach ($result as $print) {

              ?>

                <tr id="user_<?php echo $print->user_id; ?>">

                  <td width='5%' id=""><?php echo $print->user_id; ?></td>

                  <td width='20%' id="inputUsername_<?php echo $print->user_id; ?>"><?php echo $print->name; ?></td>

                  <td width='20%' id="inputUserEmail_<?php echo $print->user_id; ?>"><?php echo $print->email; ?></td>

                  <td width='45%'> <img id="inputUserFile_<?php echo $print->user_id; ?>" height="250px" width="250px" src="<?php echo $print->filepath; ?>" alt=""> </td>

                  <td width='10%'>

                    <form name="formaction_<?php echo $print->user_id; ?>" id="formaction_<?php echo $print->user_id; ?>">

                      <input type="hidden" name="userid_delete" id="userid_delete" value="<?php echo $print->user_id; ?>">

                    <!-- <a href='admin.php?page=crud%2Fcrud.php&upt=$print->user_id'>

                      <button type='button'>UPDATE</button>

                    </a>  -->

                    <a href="#edit_user" class="open-edit_user" data-toggle="modal" data-user_id="<?php echo $print->user_id; ?>" onclick="goDoSomething(this);"> 

                      <span class="glyphicon glyphicon-edit">EDIT</span> 

                    </a>

                    <!-- <a href='admin.php?page=crud%2Fcrud.php&del=$print->user_id'> -->

                      <button type='button' data-user_id="<?php echo $print->user_id; ?>" onclick="DeleteData(this);">DELETE</button>

                    <!-- </a> -->

                  </form>

                  </td>

                </tr>

              

           <?php }

          }

        ?>

      </tbody>  

    </table>

    <br>

    <br>

    

  </div>

<?php

}


function edit_data(){

?>

<div class="modal fade" id="edit_user" role="dialog"> 

  <div class="modal-dialog">   

    <div class="modal-content"> 

      <div class="modal-header">   

        <h4 class="modal-title">

          <b>User Registration EDIT Form</b>

          <span id="uid"> </span>

        </h4> 

        <button type="button" class="close" data-dismiss="modal">&times;</button>   

      </div> 

      <div class="modal-body">   

        <div class="fetched_user"></div> 

        <div class="wqsubmit_message1"></div>


          <form name="editform" id="editform">

            <table>

              <tbody>

                <tr>

                  <td><input id="userid_input" type="text" value="" disabled>

                      <input type="hidden" name="userid" id="userid" value="">

                  </td>

                </tr>

                <tr>

                  <td><input type="text" id="editnewname" name="editnewname" placeholder="Name Here"></td>

                </tr>

                <tr>

                  <td><input type="text" id="editnewemail" name="editnewemail" placeholder="Email ID Here"></td>

                </tr>

                <tr>

<td>

<img src="" id="editfile" name="editfile" width="250px" height="250px">

<input type="hidden" id="editfile_hidden" name="editfile_hidden" value="">

<input type="file" name="fileedit" id="fileedit" value="">

</td>

                </tr>

              </tbody>

            </table>

          

          </form>

      </div> 

      <div class="modal-footer">

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        <button type="button" class="btn btn-primary" id="updatedata" name="updatedata" >Update Data</button>

      </div> 

    </div>

  </div>

</div> <!--Edit Modal close-->

<?php

}


//deactive plugin

register_deactivation_hook( __FILE__, 'deactivate_crudfunction' );

function deactivate_crudfunction(){

global $wpdb;

  $table_name = $wpdb->prefix . 'crudfront';

  $sql = "DROP TABLE IF EXISTS $table_name";

  $wpdb->query($sql);

}


FILE : ajax_action.php

<?php
add_action('wp_ajax_ajaxfrontend','ajax_front_insert');
add_action('wp_ajax_nopriv_ajaxfrontend','ajax_front_insert');

function ajax_front_insert() {
  global $wpdb;
  //print_r($_POST); print_r($_FILES['file']); exit;
  $table_name = $wpdb->prefix . 'crudfront';
  //echo $filename=$_FILES['file1']['name']; exit();

  //file upload

  if (isset($_FILES['file1'] ) && !empty($_FILES['file1']['name']) ){
    $allowedExts = array("jpeg", "jpg", "png", "bmp", "gif");
    $temp = explode(".", $_FILES["file1"]["name"]);
    $extension = end($temp);
    if ( in_array($extension, $allowedExts)){
       if ( ($_FILES["file1"]["error"] > 0) && ($_FILES['file1']['size'] <= 3145728 ))
        {
            $response = array(
                "status" => 'error',
                "message" => 'ERROR Return Code: '. $_FILES["file1"]["error"],
                );
        }
        else{
          $uploadedfile = $_FILES['file1'];
          $upload_name = $_FILES['file1']['name'];
          $tempname = $_FILES["file1"]["tmp_name"];
          //$uploads = wp_upload_dir();
          //$filepath = $uploads['path']."/$upload_name";
          $filepath = MY_FRONT_CRUDPATH."imgs/$upload_name";
          if ( ! function_exists( 'wp_handle_upload' ) )
          {
              require_once( ABSPATH . 'wp-admin/includes/file.php' );
          }
          require_once( ABSPATH . 'wp-admin/includes/image.php' );
          $upload_overrides = array( 'test_form' => false );
          $movefile = wp_handle_upload( $uploadedfile, $upload_overrides ); // default wordpress file upload
          //$movefile = wp_upload_bits($uploadedfile, null, file_get_contents($_FILES["file1"]["tmp_name"]));
          //$movefile = move_uploaded_file($tempname,$filepath);
          if ( $movefile && !isset( $movefile['error'] )  ) {
              $file = $movefile['file'];
              $url = $movefile['url'];
              $type = $movefile['type'];

              $attachment = array(
                  'post_mime_type' => $type ,
                  'post_title' => $upload_name,
                  'post_content' => 'File '.$upload_name,
                  'post_status' => 'inherit'
                  );

              $attach_id=wp_insert_attachment( $attachment, $file, 0);
              $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
              wp_update_attachment_metadata( $attach_id, $attach_data );
          }
          $response = array(
            "status" => 'success',
            "url" => $url
          );


        }

    }
    else
    {
        $response = array(
            "status" => 'error',
            "message" => 'something went wrong, most likely file is to large for upload. check upload_max_filesize, post_max_size and memory_limit in you php.ini',
            );
    }
  } else {
    // no file uploaded {"status":"success","url":"http:\/\/localhost\/wordpress63\/wp-content\/uploads\/2022\/12\/blue-smart-watch-1.jpg"} Data Has Inserted Successfully

    $upload_name = '';
    
  }
  //print json_encode($response);
  //exit;
  //end file upload
  $sql = "SELECT * FROM `$table_name` WHERE `name` = '".$_POST['newname']."' AND `email` = '".$_POST['newemail']."' ORDER BY `user_id` DESC" ;
  //echo $sql;
  $wpdb->get_row($sql);
  if($wpdb->num_rows < 1) {
    $query = $wpdb->insert($table_name , array(
      "name" => $_POST['newname'],
      "email" => $_POST['newemail'],
      "filepath" => $url
    ));

    $last_query = $wpdb->last_query;
    if ($query == true) {
      //$response = array('message'=>'Data Has Inserted Successfully', 'rescode'=>200);
      $response = '<span class="alert alert-success"> Data Has Inserted Successfully </span>';
    } else {
       $response = '<span class="alert alert-danger"> Data Not Saved </span>';
    }
    
  } else {
    $response = '<span class="alert alert-info"> Data Has Already Exist </span>';
  }
  echo $response;
  exit();
  wp_die();
}



add_action('wp_ajax_edituserdata','ajaxEditData');
add_action('wp_ajax_nopriv_edituserdata','ajaxEditData');

function ajaxEditData() {
  global $wpdb;
  $table_name = $wpdb->prefix . 'crudfront';
  $wpdb->get_row( "SELECT * FROM `$table_name` WHERE `name` = '".$_POST['editnewname']."' AND `email` = '".$_POST['editnewemail']."' AND `user_id`!='".$_POST['userid']."' " );
  if($wpdb->num_rows < 1) {

    //file upload
    if (isset($_FILES['fileedit'] ) && !empty($_FILES['fileedit']['name']) ){
      $allowedExts = array("jpeg", "jpg", "png", "bmp", "gif");
      $temp = explode(".", $_FILES["fileedit"]["name"]);
      $extension = end($temp);
      if ( in_array($extension, $allowedExts)){
         if ( ($_FILES["fileedit"]["error"] > 0) && ($_FILES['fileedit']['size'] <= 3145728 ))
          {
              $response = array(
                  "status" => 'error',
                  "message" => 'ERROR Return Code: '. $_FILES["fileedit"]["error"],
                  );
          }
          else{
            $uploadedfile = $_FILES['fileedit'];
            $upload_name = $_FILES['fileedit']['name'];
            $tempname = $_FILES["fileedit"]["tmp_name"];
            //$uploads = wp_upload_dir();
            //$filepath = $uploads['path']."/$upload_name";
            $filepath = MY_FRONT_CRUDPATH."imgs/$upload_name";
            if ( ! function_exists( 'wp_handle_upload' ) )
            {
                require_once( ABSPATH . 'wp-admin/includes/file.php' );
            }
            require_once( ABSPATH . 'wp-admin/includes/image.php' );
            $upload_overrides = array( 'test_form' => false );
            $movefile = wp_handle_upload( $uploadedfile, $upload_overrides ); // default wordpress file upload
            //$movefile = wp_upload_bits($uploadedfile, null, file_get_contents($_FILES["file1"]["tmp_name"]));
            //$movefile = move_uploaded_file($tempname,$filepath);
            if ( $movefile && !isset( $movefile['error'] )  ) {
                $file = $movefile['file'];
                $url = $movefile['url'];
                $type = $movefile['type'];

                $attachment = array(
                    'post_mime_type' => $type ,
                    'post_title' => $upload_name,
                    'post_content' => 'File '.$upload_name,
                    'post_status' => 'inherit'
                    );

                $attach_id=wp_insert_attachment( $attachment, $file, 0);
                $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
                wp_update_attachment_metadata( $attach_id, $attach_data );
            }
            $response = array(
              "status" => 'success',
              "url" => $url
            );


          }

      }
      else
      {
          $response = array(
              "status" => 'error',
              "message" => 'something went wrong, most likely file is to large for upload. check upload_max_filesize, post_max_size and memory_limit in you php.ini',
              );
      }
    } else {
      // no file uploaded {"status":"success","url":"http:\/\/localhost\/wordpress63\/wp-content\/uploads\/2022\/12\/blue-smart-watch-1.jpg"} Data Has Inserted Successfully
      //$upload_name = $_POST['editfile_hidden'];
      $url = $_POST['editfile_hidden'];
    }

    $updatedata = $wpdb->update( $table_name, array(
      "name" => $_POST['editnewname'],
      "email" => $_POST['editnewemail'],
      "filepath" => $url
      //"updated_at" => time()
    ), array('user_id' => $_POST['userid']) );

    //echo $last_query = $wpdb->last_query;

    if ($updatedata == true) {
      //$response = array('message'=>'Data Has Updated Successfully', 'rescode'=>200);
      $response = '<span class="alert alert-success"> Data Has Updated Successfully </span>';
    } else {
      $response = '<span class="alert alert-danger"> Data Not Saved </span>';
    }


    
  } else {
    //$response = array('message'=>'Data Has Already Exist', 'rescode'=>404);
    $response = '<span class="alert alert-warning"> Data Has Already Same! </span>';
  }
  //echo json_encode($response);
  echo $response;
  exit();
  wp_die();
}


add_action('wp_ajax_delete_data','wqedit_entry_delete_data');
add_action('wp_ajax_nopriv_delete_data','wqedit_entry_delete_data');
function wqedit_entry_delete_data() {
  global $wpdb;
  $table_name = $wpdb->prefix . 'crudfront'; 
  //$_POST['editnewname'];
  //print_r($_POST); exit(); 
  $userid_delete = $_POST['userid_delete'];
  $query = $wpdb->delete( $table_name, array( 'user_id' => $userid_delete ) );
  //echo $last_query = $wpdb->last_query;
  if ($query == true) {
    $response = "1";
  } else {
    $response = "2";
  }
  echo $response;
  exit();
  wp_die();
}

FILE : css/style.css


.wqmessage {
  color: red;
  font-size: 16px;
}
.wqsubmit_message {
  font-size: 16px;
}
.wqtextfield {
  width: 100%;
  padding: 15px;
  border: 1px solid #ccc;
  border-radius: 8px;
}
.wqsubmit_button {
  background-color: lightseagreen;
  border: none;
  color: white;
  padding: 10px;
  cursor: pointer;
  border-radius: 8px;
  width: 100%;
}
.wqlabel {
  font-size: 20px;
  margin-bottom: 10px;
}
.wqpage_heading {
  font-size: 25px;
  text-align: center;
}

#insertform {
    float: left;
    padding-top: 20px;
}
.wqsubmit_message{padding: 10px;}


FILE: js/crud.js

jQuery(document).ready(function(){
   //$(document).on('submit','#insertform', function(e) {
   jQuery("#savedata").click( function(e) {
    e.preventDefault();
    //alert('aaya');
    $('.wqmessage').html('');
    $('.wqsubmit_message').html('');

      var newname = $('#newname').val();
      var newemail = $('#newemail').val();

      var regex = /^([_\-\.0-9a-zA-Z]+)@([_\-\.0-9a-zA-Z]+)\.([a-zA-Z]){2,7}$/;
      if(regex.test(newemail)){
       var emailcheck = true;
      }
      else{
       var emailcheck = false;
      }


    if(newname != '' && emailcheck == true) {
      var fd = new FormData(document.getElementById("insertform"));
      //var fd = new FormData(this);
      var action = 'ajaxfrontend';
      fd.append("action", action);

      //var form_data =jQuery('#insertform').serializeArray();
      //console.log(form_data);


      $.ajax({
        data: fd,
        //data: {action: "wqnew_entry", newname : newname, newemail: newemail},
        type: 'POST',
        url: ajax_var.ajaxurl,
        contentType: false,
           cache: false,
           processData:false,
        success: function(response) {
         //var res = JSON.stringify(response);
          //var res = JSON.parse(res);
          $('.wqsubmit_message').html(response);
          // if(res.rescode!='404') {
          //   $('#insertform')[0].reset();
          //   $('.wqsubmit_message').css('color','green');
          // } else {
          //   $('.wqsubmit_message').css('color','red');
          // }
          setTimeout(function() { location.reload(); }, 3500);
          //$(".entry-content").load("../showdata.php");
        }
      });
    } else {
      return false;
    }
  });



   //update data
   jQuery("#updatedata").click( function(e) {
      e.preventDefault();
      $('.wqmessage').html('');
      $('.wqsubmit_message1').html('');
      var userid = $('#userid').val();
      var editnewname = $('#editnewname').val();
      var editnewemail = $('#editnewemail').val();

      var regex = /^([_\-\.0-9a-zA-Z]+)@([_\-\.0-9a-zA-Z]+)\.([a-zA-Z]){2,7}$/;
      if(regex.test(editnewemail)){
       var emailcheck = true;
      }
      else{
       var emailcheck = false;
      }

      if(newname != '' && emailcheck == true) { 
        var fd = new FormData(document.getElementById("editform"));
        var action = 'edituserdata';
        fd.append("action", action);
//debugger;
        $.ajax({
          data: fd,
          type: 'POST',
          url: ajax_var.ajaxurl,
          contentType: false,
             cache: false,
             processData:false,
          success: function(response) {
            $('.wqsubmit_message1').html(response);
            setTimeout(function() { location.reload(); }, 3500);
          }
        });        
      }
      else {
        return false;
      }
   });

  });

function goDoSomething(d){     
    var uid = d.getAttribute("data-user_id");
    var username = $("#inputUsername_"+uid).text();
    var emailid = $("#inputUserEmail_"+uid).text();
    var filesrc = $("#inputUserFile_"+uid).attr('src');
    $("#userid_input").val(uid); 
    $("#userid").val(uid); 
    $("#editnewname").val(username);
    $("#editnewemail").val(emailid);
    //$('#editfile').attr('src','');
    $('#editfile').attr('src',filesrc);
    $('#editfile_hidden').val(filesrc);
}

//delete data
function DeleteData(d){ 
  var uid = d.getAttribute("data-user_id");
  //alert(uid);
  if (confirm('Are you sure ?')) {
        //$(this).prev('span.text').remove();
      //alert(uid);
    $('#msg').html('');
    var fd = new FormData(document.getElementById("formaction_"+uid));
    var action = 'delete_data';
    fd.append("action", action);
    $.ajax({
          data: fd,
          type: 'POST',
          url: ajax_var.ajaxurl,
          contentType: false,
             cache: false,
             processData:false,
          success: function(res) {
            $('#msg').html('<span class="alert alert-success"> Data Has DELETED Successfully </span>');
            $('#user_'+uid).remove();
            //setTimeout(function() { location.reload(); }, 4000);
          }
    });
  }
}

Now go to wp-admin area. open any page/post. Paste this shortcode to this : 
[frontendcrudnew]


These are some screenshots.





Thursday, April 27, 2017

5 File Upload Plugins in jQuery

Here i explain some file upload plugins in jQuery. I hope these will help you.

1. Uploadify

Uploadify™ is a jQuery plugin that allows you to easily add multiple file upload functionality to your website. Two distinct versions (HTML5 and Flash) allow you the flexiblity to choose the right implementation for your site and fallback methods make it degrade gracefully.
Features:
* Multiple File Uploads
* Drag and Drop
* Real-Time Progress Indicators
* Custom Upload Restrictions
* Extreme Customization

DEMO / DOWNLOAD 

 

2. Fileuploader

Beautiful and powerful HTML5 file uploading tool. A jQuery and PHP plugin that transforms the standard file input into a revolutionary and fancy field on your page.You can very easy design your own input and file preview elements with HTML/CSS and jQuery. We have also prepared 4 responsive and clean templates that you can use.It is very easy to implement the Fileuploader plugin into your Webpage, also based on WordPress, Joomla, TYPO3, Laravel and others.
Features:
* Design your own input
* Add files from different folders
* Drag&Drop and Ajax upload
* Enable the edit mode
* Validate and control

DEMO / DOWNLOAD 

 

3. Plupload

Plupload using HTML5 APIs. Always. Plupload is based on multi-runtime pollyfills for XMLHttpRequest L2, File and Image APIs. So when there’s no HTML5 available in the browser.Files that have to be uploaded can be small or huge – about several gigabytes in size. In such cases standard upload may fail, since browsers still cannot handle it properly. We slice the files in chunks and send them out one by one. You can then safely collect them on the server and combine into original file.
Features:
* Upload in HTML5
* Drag’n’Drop Files from Desktop
* Access Raw File Data
* Shrink Images on Client-Side
* Upload in Chunks
* Translated to 30+ Languages

DEMO / DOWNLOAD 

 

4. jQuery Upload File

jQuery File UPload plugin provides Multiple file uploads with progress bar. jQuery File Upload Plugin depends on Ajax Form Plugin, So Github contains source code with and without Form plugin.
Features:
* Single File Upload
* Multiple file Upload (Drag & Drop)
* Sequential file upload
* File Restrictions
* Localization (Multi-language)
* Sending Form Data
* Adding HTML elements to progressbar
* Custom UI
* Upload Events
* Delete / Download Uploaded files
* Image Preview
* Show previous uploads

DEMO / DOWNLOAD 

 

5. jQuery File Upload

File Upload widget with multiple file selection, drag&drop support, progress bars, validation and preview images, audio and video for jQuery UI.
Supports cross-domain, chunked and resumable file uploads and client-side image resizing.
Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads.

DEMO / DOWNLOAD

Wednesday, February 22, 2017

File size and extension validation before upload in javascript

It is a good idea to apply quick client side validation on file / image upload in javaScript, You can easily check file extension and size before file upload, So that user won’t be allow to upload garbage and large size of files. And this is good approach to maintain good server health to prevent garbage files.
 Full Code :

<div style="margin:0 auto; width:50% text-align:center">
<form id="form">
    <input type='file' id="file" />
    <br/>
   <span style="color:red"> Note: Please select only image file (eg: .png, .jpeg, .jpg, .gif etc)<br/> Max File size : 1MB allowed </span><br/>
    <img id="img" src="http://placehold.it/200x200" alt="No image uploaded" />
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(function() {
$("#file").change(function () {
        if(fileExtValidate(this)) {
             if(fileSizeValidate(this)) {
                 showImg(this);
             }   
        }   
    });

// File extension validation, Add more extension you want to allow
var validExt = ".png, .gif, .jpeg, .jpg";
function fileExtValidate(fdata) {
 var filePath = fdata.value;
 var getFileExt = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
 var pos = validExt.indexOf(getFileExt);
 if(pos < 0) {
     alert("This file is not allowed, please upload valid file.");
     return false;
  } else {
      return true;
  }
}

// file size validation
// size in kb
var maxSize = '1024';
function fileSizeValidate(fdata) {
     if (fdata.files && fdata.files[0]) {
                var fsize = fdata.files[0].size/1024;
                if(fsize > maxSize) {
                     alert('Maximum file size exceed, This file size is: ' + fsize + "KB");
                     return false;
                } else {
                    return true;
                }
     }
 }

 // display img preview before upload.
function showImg(fdata) {
        if (fdata.files && fdata.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#img').attr('src', e.target.result);
            }

            reader.readAsDataURL(fdata.files[0]);
        }
    }
});
</script>