File Upload with Progress Bar

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 65

File Upload with Progress Bar

Hi,
How to upload a file and display a progress bar, percentages "%" of the upload progress, without refreshing the page? I think it is something with Ajax.
And, is it possible to check the file type before submitting for upload?

Thank you.

MarPlo
Hi
Try this script. It uses jQuery and form plugin; also, it checks the file type before upload.
To auto submit the file, without to click the submit button, replace $('#'+ idf).ajaxForm with:
$('#'+ idf).ajaxSubmit .

html file:

Code: Select all

<form action="upload.php" id="fupl" method="post" enctype="multipart/form-data">
  <input type="file" name="fileup" id="fileup" /><br/>
  <input type="submit" value="Send" />
</form>
<div class="progress">
  <div class="bar"></div>
  <div class="percent"></div>
</div>
<div id="status"></div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// Upload file with status bar percentage ( https://coursesweb.net/ )

// extensions of the allowed files to upload, separated by "|"
var allowed_files = 'gif|jpg|jpe|jpeg|mp3|png';

// to submit the form with ajax from jquery.form.js plugin
// receives the form id
function ajaxFrm(idf) {
  var bar = $('.bar');
  var percent = $('.percent');
  var status = $('#status');

  // sends the form data
  // use ajaxSubmit to auto submit the form
  $('#'+ idf).ajaxForm({
    beforeSend: function() {
      status.empty();
      var percentVal = '0%';
      bar.width(percentVal)
      percent.html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
      var percentVal = percentComplete + '%';
      bar.width(percentVal)
      percent.html(percentVal);
    },
    complete: function(xhr) {
      bar.width("100%");
      percent.html("100%");
      status.html(xhr.responseText);
    }
  });
  return false;
}

// register "change" event on the input field for upload-file
document.getElementById('fileup').addEventListener('change', function(e){
  var getval = e.target.value;
  // check file extension
  if(getval.match(new RegExp(allowed_files, 'i')) == null) alert('This type of file is not allowed for upload');
  else ajaxFrm('fupl');
});     
</script>
upload.php :

Code: Select all

<?php
// Simple PHP Upload Script:  https://coursesweb.net/php-mysql/

$uploadpath = 'files/';      // directory to store the uploaded files (relative to this file)
$max_size = 2000;          // maximum file size, in KiloBytes
$alwidth = 900;            // maximum allowed width, in pixels
$alheight = 800;           // maximum allowed height, in pixels
$allowtype = array('bmp', 'gif', 'jpg', 'jpe', 'mp3', 'png');        // allowed extensions

if(isset($_FILES['fileup']) && strlen($_FILES['fileup']['name']) > 1) {
  $uploadpath = $uploadpath . basename( $_FILES['fileup']['name']);       // gets the file name
  $sepext = explode('.', strtolower($_FILES['fileup']['name']));
  $type = end($sepext);       // gets extension
  list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']);     // gets image width and height
  $err = '';         // to store the errors

  // Checks if the file has allowed type, size, width and height (for images)
  if(!in_array($type, $allowtype)) $err .= 'The file: <b>'. $_FILES['fileup']['name']. '</b> not has the allowed extension type.';
  if($_FILES['fileup']['size'] > $max_size*1000) $err .= '<br/>Maximum file size must be: '. $max_size. ' KB.';
  if(isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight)) $err .= '<br/>The maximum Width x Height must be: '. $alwidth. ' x '. $alheight;

  // If no errors, upload the image, else, output the errors
  if($err == '') {
    if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) { 
      echo 'File: <b>'. basename( $_FILES['fileup']['name']). '</b> successfully uploaded:';
      echo '<br/>File type: <b>'. $_FILES['fileup']['type'] .'</b>';
      echo '<br />Size: <b>'. number_format($_FILES['fileup']['size']/1024, 3, '.', '') .'</b> KB';
      if(isset($width) && isset($height)) echo '<br/>Image Width x Height: '. $width. ' x '. $height;
      echo '<br/><br/>Image address: <b>http://'.$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['REQUEST_URI']), '\\/').'/'.$uploadpath.'</b>';
    }
    else echo '<b>Unable to upload the file.</b>';
  }
  else echo $err;
}

Similar Topics