Showing posts with label progress bar. Show all posts
Showing posts with label progress bar. Show all posts

Friday, May 9, 2014

Multiple File upload with Ajax

Sry Guyz for the late post. I was out of station thats why and my gf my computer was not with me but now I Am Back. In this post we i will show how to create a awsm Multiple File upload with percentage and results with ajax. So get Started.

Live Demo Watch Video Tutorial Download Script

html

markup for this is very simple we are just using a <form> with <input type="file"> and Submit button and we have give the multiple attribute to the file so that the user can select multiple file. We have created 3 empty div for putting result via javascript
<form action="upload.php" method="post" enctype="multipart/form-data">
 <fieldset>
  <legend>File upload</legend>
  <input type="file" name="file[]" id="file" multiple required/>
  <input type="submit" name="upload" id="upload"/>

  <div id="per"></div>
  <div id="sucess"></div>
  <div id="error"></div>
 </fieldset>
</form>

php

In this php script we are getting the file from the html file and checking it if the file is valid we r uploading the file and stroing it in a array else we are storing the error message in a array and in last we are encoding the success and error array into json format
<?php
header('Content-Type: application/json');

//function to get the extension of the file
function getExt($name){
 $array = explode(".", $name);
 $ext = strtolower(end($array));
 return $ext;
}

//create global array
$allowed = array('gif', 'png', 'jpg');
$success = array();
$error = array();

if(isset($_FILES['file']) && !empty($_FILES['file'])){
  foreach ($_FILES['file']['name'] as $key => $name) {
   $tmp = $_FILES['file']['tmp_name'][$key];
   $ext = getExt($name);
   $size = $_FILES['file']['size'][$key];

   // check the extension is valid or not
   if(in_array($ext, $allowed) == true){
    $filename = md5($name) . time() .'.'.$ext;
    //check the size of the file
    if($size <= 2097152){
     if(move_uploaded_file($tmp, 'uploads/'.$filename) === true){
      $success[] = array('name' => $name, 'location' => 'uploads/'.$filename);
     }else{
      $error[] = array('name' => $name, 'msg' => 'File is not uploaded');
     }
    }else{
     $error[] = array('name' => $name, 'msg' => 'File size more than 2MB');
    }
   }else{
    $error[] = array('name' => $name, 'msg' => 'File Type not allowed');
   }
  }
  
  //encode the result in json format
  $json = json_encode(array(
   'success' => $success,
   'error' => $error
  ));

  echo $json;
  exit();
}
?>

javascript

we are sending a XMLHttpRequest to the server and displaying the response given by the upload.php page back to the user in empty div which we have created earlier 
<script type="text/javascript">
 var form = document.querySelector('#upload'),
   fileToUpload = document.querySelector('#file'),
  button = document.querySelector('#submit'),
  per = document.querySelector('#percentage'),
  sucessDiv = document.querySelector('#success'),
  errorDiv = document.querySelector('#failed'),
  sucessMarkup = '',
  errorMarkup = '';

 form.addEventListener('submit', function(e){
  e.preventDefault();

  var files = fileToUpload.files;

  var formdata = new FormData();

  //loop throught all the files

  for (var i = 0; i < files.length; i++) {
   var file = files[i];

   formdata.append('file[]', file);
  }

  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'upload.php');

  xhr.addEventListener('readystatechange', function(){
   if(xhr.readyState === 4){
    if(xhr.status === 200){
     var uploaded = JSON.parse(xhr.response);
     //put the json response to the div
     //success files 
     for(var i = 0; i < uploaded.success.length; i++){
      var name = uploaded.success[i].name;
      var location = uploaded.success[i].location;

      sucessMarkup += "<a href='view.php?id="+location+"' target='_blank'>"+name+"</a>";
     }

     //error file

     for (var i = 0; i < uploaded.error.length; i++) {
      var name = uploaded.error[i].name;
      var msg = uploaded.error[i].msg;

      var errorH1 = document.createElement('h2');
      errorH1.innerHTML = 'Unfortunately '+uploaded.error.length+' files are not uploaded';
      errorDiv.appendChild(errorH1);
      errorMarkup += '<p>'+name+' - '+msg+'</p>';
     };
     
     //put the results in the div
     sucessDiv.innerHTML = sucessMarkup;
     errorDiv.innerHTML = errorMarkup;
    }
   }else{
    console.log('error');
   }
  }, false);
 
  //code for showing the upload percenatge
  xhr.upload.addEventListener('progress', function(e){
   if(e.lengthComputable === true){
    var per = Math.round((e.loaded / e.total) * 100);
    percentage.innerHTML = per + '% uploaded';
   }
  })

  
  xhr.send(formdata);

 }, false);
</script>

Thursday, April 10, 2014

File Upload with Progress bar by Raw AJAX & php

Hey Guyz in the tutorial i am going to teach you how to create a file upload system with progress bar with raw ajax. This is very useful for the hosting website because it give a great feedback to the user how much their file has been uploaded. This type to project can be created easily with a code library like jQuery but its greate to create it via raw ajax it give a greate understanding that what is going on
live Demo Download Watch Video

html

html markup is super easy in this we have a form a progressbar and a empty status div
<form action="upload_back.php" method="post" enctype="multipart/form-data" id="form">
  <input type="file" name="file1" id="file1">
  <input type="submit" name="submit" id="submit" value="upload"> 
 </form>
 <br>
 <div style="width:400px;">
  <div id="progressbar">
   <div id="progress" style="width:0px;"></div>
  </div>
 </div>
 <div id="status"></div>

css

in css we are designing the progress bar fro more details view my previous post on Css3 Progress Bar
<style type="text/css">
#progressbar{
 width: 100%;
 background: #eee;
 padding: 3px;
 border-radius: 3px;
 box-shadow: inset 0px 1px 3px rgba(0,0,0,0.2);
 }
#progress{
 height: 20px;
 background: cornflowerblue;
 display: block;
 border-radius: 3px;
 -webkit-transition: width 0.8s ease;
 -moz-transition: width 0.8s ease;
 transition: width 0.8s ease;
}
</style>

JavaScript

in javascript we are sending the uploded data to the upload_back.php page and by diving the kb send and total kb we get the percentage of how much the file is uploaded
<script type="text/javascript">
 var ajax = new XMLHttpRequest();
 function $(id){
  return document.getElementById(id);
 }
 function upload(e){
  e.preventDefault();
  var file = $("file1").files[0];
  var formdata = new FormData();
  formdata.append('file1', file);

  ajax.upload.addEventListener('progress', progressHandler, false);
  ajax.addEventListener('load', completeHandler, false);
  ajax.addEventListener('abort', abortHandler, false);
  ajax.addEventListener('error', errorHandler, false);
  ajax.open('POST', 'upload_back.php');
  ajax.send(formdata);
 }

 function progressHandler(e){
  var percent = (e.loaded / e.total) * 100;
  percent = Math.round(percent);
  $('progress').style.width = Math.round(percent)+'%';
  $('status').innerHTML = percent + '% uploaded plzz wait.....';
 }
  function completeHandler(){
   $('status').innerHTML = ajax.responseText;
   $('progress').style.width = '0%';
  }

  function abortHandler(){
   alert('file upload aborted');
  }

  function errorHandler(){
   alert('file upload has an error');
  }
         //when form is submited
 $('form').addEventListener('submit', upload, false);

</script>

upload_back.php

in php file first we are getting the extension of the image and if iuts valid then we upload the file and show the link
<?php
 function getext($img){
  $name = strtolower($img);
  $data = explode(".", $name);
  $ext = count($data) -1;
  return $data[$ext];
 }
 if(isset($_FILES)){
  $allowed = array('jpg','png','gif');
  $ext = getext($_FILES['file1']['name']);
  $size = $_FILES['file1']['size'];
  if(in_array($ext, $allowed)){
   if($size < 2097152){
    $name = $_FILES['file1']['name'];
    if(move_uploaded_file($_FILES['file1']['tmp_name'], './upload/'.$name)){
     echo '<a href="./upload/'.$name.'">'.$name.'</a>';
    }else{
     echo "file upload has an error";
    }
   }else{
    echo "File size more than <strong>2MB<strong>";
   }
  }else{
   echo "file type not allowed";
  }
 }else{
  echo "not";
 }
?>

Monday, February 17, 2014

Css3 Progress Bar

Now a days progress bar is a very important in any social media website and progress bar is very easy to create with just a few lines of css and some beautifull css3 transition
CSS3 Progress Bar

Download Script View Demo 

html

html is very simple it just have a div with class .bar and a span inside the div
<div class="bar">
 <span style="width:0%;"></span>
</div>

css

//style of div
.bar{
 width: 100%;
 background: #eee;
 padding: 3px;
 border-radius: 3px;
 box-shadow: inset 0px 1px 3px rgba(0,0,0,0.2);
}
//style of span
.bar span{
 height: 20px;
 background: cornflowerblue;
 display: block;
 border-radius: 3px;
 -webkit-transition: width 0.8s ease;
 -moz-transition: width 0.8s ease;
 transition: width 0.8s ease;
}

Like Us on Facebook / Add Hunk As Friend