HTML5 Drag and Drop Multiple File Uploader

Our new article is going to tell you about HTML5 file upload. Yes, I explained basics of html5 file upload in the past (in one of our previous articles), but today I would like to give you another example, the better one. Now, you can just drag and drop your images (multiple images) in order to start uploading. Plus, the script displays overall progress (in percentage, plus – files left) and server response (without actual uploading). I am going to display progress at CANVAS element in realtime. And, at the last – our script can upload files not only into own server, but to another too (we can say, that this is cross-site uploader).

Here are our demo and downloadable package:

Live Demo

[sociallocker]

download in package

[/sociallocker]


Ok, download the sources and lets begin !


Step 1. HTML

As the first – html markup:

index.html

01 <div class="container">
02     <div class="contr"><h2>Drag and Drop your images to 'Drop Area' (up to 5 files at a time, size - under 256kb)</h2></div>
03     <div class="upload_form_cont">
04         <div id="dropArea">Drop Area</div>
05         <div class="info">
06             <div>Files left: <span id="count">0</span></div>
07             <div>Destination url: <input id="url" value="https://www.script-tutorials.com/demos/257/upload.php"/></div>
08             <h2>Result:</h2>
09             <div id="result"></div>
10             <canvas width="500" height="20"></canvas>
11         </div>
12     </div>
13 </div>
14 <script src="js/script.js"></script>

As you can see, it consists of several main elements: ‘Drop area’ at the left and ‘Info block’ at the right. When we drag and drop image files on our dropArea, in the Info block we will get response from server. Pay attention, that there is ‘Destination url’ element. Right now it connected to our server. But you can change it to your url anytime.

Step 2. CSS

css/main.css

Now, its time to customize our layout:

css/main.css

01 .container {
02     overflow:hidden;
03     width:960px;
04     margin:20px auto;
05 }
06 .contr {
07     background-color#212121;
08     color#FFFFFF;
09     padding10px 0;
10     text-aligncenter;
11     border-radius:10px 10px 0 0;
12     -moz-border-radius:10px 10px 0 0;
13     -webkit-border-radius:10px 10px 0 0;
14 }
15 .upload_form_cont {
16     background: -moz-linear-gradient(#ffffff#f2f2f2);
17     background: -ms-linear-gradient(#ffffff#f2f2f2);
18     background: -webkit-gradient(linear, left topleft bottom, color-stop(0%#ffffff), color-stop(100%#f2f2f2));
19     background: -webkit-linear-gradient(#ffffff#f2f2f2);
20     background: -o-linear-gradient(#ffffff#f2f2f2);
21     filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#f2f2f2');
22     -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#f2f2f2')";
23     background: linear-gradient(#ffffff#f2f2f2);
24     color#000;
25     overflowhidden;
26 }
27 .info {
28     background-color#EEEEEE;
29     border1px solid #DDDDDD;
30     floatleft;
31     font-weightbold;
32     height530px;
33     margin20px;
34     positionrelative;
35     width560px;
36 }
37 .info > div {
38     font-size14px;
39     font-weightbold;
40     padding10px 15px 5px;
41 }
42 .info > h2 {
43     padding0 15px;
44 }
45 .info > canvas {
46     margin-left15px;
47     margin-bottom10px;
48 }
49 .info #url {
50     width400px;
51 }
52 #dropArea {
53     background-color#DDDDDD;
54     border3px dashed #000000;
55     floatleft;
56     font-size48px;
57     font-weightbold;
58     height530px;
59     line-height530px;
60     margin20px;
61     positionrelative;
62     text-aligncenter;
63     width300px;
64 }
65 #dropArea.hover {
66     background-color#CCCCCC;
67 }
68 #dropArea.uploading {
69     background#EEEEEE url(loading.gif) center 30% no-repeat;
70 }
71 #result .s, #result .f {
72     font-size12px;
73     margin-bottom10px;
74     padding10px;
75     border-radius:10px;
76     -moz-border-radius:10px;
77     -webkit-border-radius:10px;
78 }
79 #result .s {
80     background-color#77fc9f;
81 }
82 #result .f {
83     background-color#fcc577;
84 }

Step 3. HTML5 JS

js/script.js

001 // variables
002 var dropArea = document.getElementById('dropArea');
003 var canvas = document.querySelector('canvas');
004 var context = canvas.getContext('2d');
005 var count = document.getElementById('count');
006 var destinationUrl = document.getElementById('url');
007 var result = document.getElementById('result');
008 var list = [];
009 var totalSize = 0;
010 var totalProgress = 0;
011 // main initialization
012 (function(){
013     // init handlers
014     function initHandlers() {
015         dropArea.addEventListener('drop', handleDrop, false);
016         dropArea.addEventListener('dragover', handleDragOver, false);
017     }
018     // draw progress
019     function drawProgress(progress) {
020         context.clearRect(0, 0, canvas.width, canvas.height); // clear context
021         context.beginPath();
022         context.strokeStyle = '#4B9500';
023         context.fillStyle = '#4B9500';
024         context.fillRect(0, 0, progress * 500, 20);
025         context.closePath();
026         // draw progress (as text)
027         context.font = '16px Verdana';
028         context.fillStyle = '#000';
029         context.fillText('Progress: ' + Math.floor(progress*100) + '%', 50, 15);
030     }
031     // drag over
032     function handleDragOver(event) {
033         event.stopPropagation();
034         event.preventDefault();
035         dropArea.className = 'hover';
036     }
037     // drag drop
038     function handleDrop(event) {
039         event.stopPropagation();
040         event.preventDefault();
041         processFiles(event.dataTransfer.files);
042     }
043     // process bunch of files
044     function processFiles(filelist) {
045         if (!filelist || !filelist.length || list.length) return;
046         totalSize = 0;
047         totalProgress = 0;
048         result.textContent = '';
049         for (var i = 0; i < filelist.length && i < 5; i++) {
050             list.push(filelist[i]);
051             totalSize += filelist[i].size;
052         }
053         uploadNext();
054     }
055     // on complete - start next file
056     function handleComplete(size) {
057         totalProgress += size;
058         drawProgress(totalProgress / totalSize);
059         uploadNext();
060     }
061     // update progress
062     function handleProgress(event) {
063         var progress = totalProgress + event.loaded;
064         drawProgress(progress / totalSize);
065     }
066     // upload file
067     function uploadFile(file, status) {
068         // prepare XMLHttpRequest
069         var xhr = new XMLHttpRequest();
070         xhr.open('POST', destinationUrl.value);
071         xhr.onload = function() {
072             result.innerHTML += this.responseText;
073             handleComplete(file.size);
074         };
075         xhr.onerror = function() {
076             result.textContent = this.responseText;
077             handleComplete(file.size);
078         };
079         xhr.upload.onprogress = function(event) {
080             handleProgress(event);
081         }
082         xhr.upload.onloadstart = function(event) {
083         }
084         // prepare FormData
085         var formData = new FormData();
086         formData.append('myfile', file);
087         xhr.send(formData);
088     }
089     // upload next file
090     function uploadNext() {
091         if (list.length) {
092             count.textContent = list.length - 1;
093             dropArea.className = 'uploading';
094             var nextFile = list.shift();
095             if (nextFile.size >= 262144) { // 256kb
096                 result.innerHTML += '<div class="f">Too big file (max filesize exceeded)</div>';
097                 handleComplete(nextFile.size);
098             else {
099                 uploadFile(nextFile, status);
100             }
101         else {
102             dropArea.className = '';
103         }
104     }
105     initHandlers();
106 })();

Most of code is already commented. I hope that you can understand all this code. Anyway – some explanation how it works: in the beginning, we have linked two handlers to our DropArea: ‘drop’ and ‘dropover’. When we keep our dragged files over our Drop area, we can apply custom styles to our drop area. Then, when we drop our files, our script starts executing ‘processFiles’ function (it pushs all the dropped files into array, and starts uploading them step by step). In the result, we send data through XMLHttpRequest object to custom recipient server. During sending the files, we also display overall progress at our canvas element.

Step 4. PHP

upload.php

01 <?php
02 // set error reporting level
03 if (version_compare(phpversion(), '5.3.0''>=') == 1)
04   error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
05 else
06   error_reporting(E_ALL & ~E_NOTICE);
07 function bytesToSize1024($bytes$precision = 2) {
08     $unit array('B','KB','MB');
09     return @round($bytes / pow(1024, ($i floor(log($bytes, 1024)))), $precision).' '.$unit[$i];
10 }
11 if (isset($_FILES['myfile'])) {
12     $sFileName $_FILES['myfile']['name'];
13     $sFileType $_FILES['myfile']['type'];
14     $sFileSize = bytesToSize1024($_FILES['myfile']['size'], 1);
15     echo <<<EOF
16 <div class="s">
17     <p>Your file: {$sFileName} has been successfully received.</p>
18     <p>Type: {$sFileType}</p>
19     <p>Size: {$sFileSize}</p>
20 </div>
21 EOF;
22 else {
23     echo '<div class="f">An error occurred</div>';
24 }

Its server-side file. It doesn’t upload files of course. But it returns some information about our files (which we will display at our receiver (client) side).


Live Demo

Conclusion

Hope this helped to you! Welcome back to read our new articles about HTML5. Good luck!