HTML5 jQuery Multiple File Upload Plugin
Plupload is a cross-browser multi-runtime file uploading API. Basically, a set of tools that will help you to build a reliable and visually appealing file uploader in minutes. Historically, Plupload comes from a dark and hostile age of no HTML5, hence all the alternative fallbacks, like Flash, Silverlight and Java (still in development). It is meant to provide an API, that will work anywhere and in any case, in one way or another. While having very solid fallbacks, Plupload is built with the future of HTML5 in mind.
Prepare
The latest build is always available from download section on the Plupload site.
For the sake of simplicity let's copy the whole js/
folder to the same place where our sample html will reside.
Let's start by including js/plupload.full.min.js
. Core API doesn't depend on jQuery or any other framework, so it can be used as it is.
Add minimal HTML structure
Now we need a couple of DOM elements to turn into the main functional
components of a typical file uploader - browse button, upload button and
the file queue:
<ul id="filelist"></ul>
<br>
<div id="container">
<a id="browse" href="javascript:;">[Browse...]</a>
<a id="start-upload" href="javascript:;">[Start Upload]</a>
</div>
Let's bring these to life now.
Initialize Plupload
First, we instantiate Plupload uploader:
<script type="text/javascript">
var uploader = new plupload.Uploader({
browse_button: 'browse', // this can be an id of a DOM element or the DOM element itself
url: 'upload.php'
});
uploader.init();
</script>
Notice that we explicitly call init() method on the uploader object to actually initialize it. There's is a reason for that, but let's leave the explanation for later. For now simply remember that we call it, before we bind any event listeners to the uploader.
Typically your configuration will be larger, but for now this is all you need - browse button and url of a server-side handler, that will accept the files, do some security checks on them and finally move them to a destination folder.
Create upload handler
Let's do a couple of things right away - create destination folder - uploads/
, where we will put the files (it should have write permissions) and the upload handler - upload.php
, which will move them there.
You might not be using PHP of course, but the main logic is very simple and easily portable to any other server-side language.
<?php
if (empty($_FILES) || $_FILES["file"]["error"]) {die('{"OK": 0}');
}
$fileName = $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/$fileName");
die('{"OK": 1}');
?>
For simplicity we only move the file, without any checks (in real life this is wrong of course). Also it is better to output some response from the server (simple JSON for example), this way you will make sure that Plupload will detect the end of a request, whatever the runtime.
Example Website