Techumber
Home Blog Work

Drag n Drop MultiFile Upload with HTML5-API

Published on September 7, 2012

Our friend HTML5 supports a different varity of features. HTML5 File API is one of them. Before HTML5 there is no way we can intract with local files throught JavaScript. But with help of HTML5 File API we can intract with local file to know properties of file like file size and execute Event on files upload. In todays post we will see how to create muti file upload by drag and drop. In this post we will also some very nice feature like HTML5. Drag n Drop MultiFile Upload with HTML5-API

Demo

Download

Technologies used

1)HTML5(File API) 2)JavaScript 3)PHP

Files we are going to create:

—index.php —tuDDUpload.js —upload.php In this tutorial we will use HTML5 objects window.File, window.FileReader, window.FileList, window.Blob and HTML5 new event like dragover, drop, etc.

index.html

<html>
  <body>
    <div id="dragZone">Drop files here</div>
    <div id="result" class="mini-layout"></div>
  </body>
</html>

upload.php


<?php
if (isset($_FILES['file'])) {
if(move_uploaded_file($_FILES['file']['tmp_name'], "uploads/".$_FILES['file']['name'])){
echo "success";
}
else{
echo "fail";
}
}
exit;

tuDDUpload.js

//DDUPload Class
var DDUpload = function(options) {
  //options to local o
  this.o = options;
  var list = [],
    cur,
    dragZone = document.getElementById(this.o.dragZone),
    result = document.getElementById(this.o.resultArea),
    self = this;
  //initilize function
  this.init = function() {
    if (window.File && window.FileReader && window.FileList && window.Blob) {
      dragZone.addEventListener('dragover', this.drgFile, false);
      dragZone.addEventListener('drop', this.drpFile, false);
    } else {
      alert('Your browser doesnot support');
    }
  };
  //drag event function
  this.drgFile = function(e) {
    e.stopPropagation();
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
  };
  //drop event function
  this.drpFile = function(e) {
    e.stopPropagation();
    e.preventDefault();
    self.preview(e);
  };
  //preview function for displaying files
  this.preview = function(e) {
    var files = e.dataTransfer.files,
      output = [],
      i;
    for (i = 0, f; (f = files[i]); i++) {
      list.push(files[i]);
      output.push(
        '<div class="mini-layout"><p><b>Filename:</b>',
        escape(f.name),
        '</p>',
        '<p><b>Filetype:</b>',
        f.type,
        '</P>',
        '<p><b>Size:</b>',
        (Math.round((f.size * 100) / 1024) / 100).toString(),
        'KB</P>',
        '<p><div class="progress progress-striped active"><div class="bar" id="pb',
        i,
        '" ></div></div></p>',
        '</div>',
      );
    }
    document.getElementById('result').innerHTML = output.join('');
    self.uploadinit();
  };
  //upload intilizer
  this.uploadinit = function() {
    for (var i = 0; i < list.length; i++) {
      self.upload(list[i], i);
    }
  };
  //simple upload ajax based
  this.upload = function(ufile, i) {
    //All HTML5 browser support XMLHttpRequest so no need to create ActiveX objects.
    var xhr = new XMLHttpRequest();
    var fd = new FormData();
    fd.append('file', ufile);
    xhr.upload.addEventListener(
      'progress',
      function(e) {
        self.uploadProgress(e, i);
      },
      false,
    );
    xhr.addEventListener(
      'load',
      function(e) {
        self.uploadFinish(e, i);
      },
      false,
    );
    xhr.open('POST', self.o.uploadUrl);
    xhr.send(fd);
  };
  //upload process indicater
  this.uploadProgress = function(e, i) {
    var percent = Math.round((e.loaded * 100) / e.total);
    document.getElementById('pb' + i).style.width = percent.toString() + '%';
  };
  //upload finish
  this.uploadFinish = function(e, i) {
    document.getElementById('pb' + i).style.width = '100%';
  };
};
function initDDUpload(options) {
  //initilizing object for DDUpload class
  var dup = new DDUpload(options);
  //calling inti with object
  dup.init();
}

This is client side script. In this scrip we crated a class DDUpload. This will have following functions. init: This is the first function we will call. It will check broser support for HTML5-File api. This also fires dragoveranddrop events. drgFile: This will handle drag event. drpFile: This will handle drop event and call preview preview: This will show all added files in result area and call uploadinit. uploadinit: This will initialize file upload on files. upload: This will handle ajax uploading of files. It triggers process and load events. uploadProgress: It will show upload progress.

Calling the plugin

Add this code just before tag.

window.onload = function() {
  var options = {
    dragZone: 'dragZone',
    uploadUrl: 'upload.php',
    resultArea: 'result',
  };
  initDDUpload(options);
};

Finally we will use this script to call our JavaScript plugin. Here we can set options for draZoneuploadUrland reaultArea.