upload-file-with-ajax

Multiple File upload with Ajax




In this post we will show how to create a Multiple File upload with percentage and results with ajax, So get Started.



Multiple file upload with ajax

html

markup for this is very simple we are just using a form with Input of 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&#91;&#93;" 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&#91;'file'&#93;) && !empty($_FILES&#91;'file'&#93;)){
  foreach ($_FILES&#91;'file'&#93;&#91;'name'&#93; 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&#91;&#93; = 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&#91;i&#93;;

   formdata.append('file&#91;&#93;', 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&#91;i&#93;.name;
      var location = uploaded.success&#91;i&#93;.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&#91;i&#93;.name;
      var msg = uploaded.error&#91;i&#93;.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>

Leave a Reply

Your email address will not be published. Required fields are marked *