This fragment is about to be reported (you'll remain on this page):

You can enter a comment to clarify the mistake if you would like to:

FileDrop – cross-browser JavaScript Drag & Drop file upload

Self-contained cross-browser pure JavaScript class for Drag & Drop and AJAX (multi) file upload.

FileDrop – cross-browser JavaScript Drag & Drop file upload
  1. 1. Download & license
  2. 2. Usage
  3. 3. API
    1. 3.1. Global options
    2. 3.2. Global functions
    3. 3.3. DropHandle class
      1. 3.3.1. Events
        1. 3.3.1.1. Drag & Drop
      2. 3.3.2. Methods
    4. 3.4. FileDrop class
      1. 3.4.1. Events
      2. 3.4.2. Methods
    5. 3.5. File class
      1. 3.5.1. Events
      2. 3.5.2. Methods

FileDrop is a lightweight JavaScript class for easy-to-use file uploading that works out of the box.

Features:

  • Cross-browser – supports Firefox 3.6, Internet Explorer 6, Google Chrome 7, SRWare Iron 4, Apple Safari 5 and Opera 11.61.
  • Self-contained & tiny – just 470 lines of code; 8 KiB when minified.
  • Various callbacks – on progress, on done, on error and on many other events.
  • Graceful degradation using IFrame fallback.
  • Multiple file selection.
  • Any number of independent FileDrops.

FileDrop uses some ideas and solutions from qq FileUploader (Github) which is similar to FileDrop but almost 3 times as large (although, perhaps, more elaborated).

Relevant articles:

  1. New FileAPI usage – for Firefox
  2. GMail drag & drop – for Google Chrome (but not Safari)
  3. The XMLHttpRequest specification
  4. HTML5 Drag and Drop Upload and File API Tutorial

Download & license

FileDrop is released in public domain – feel free to use it however you like. I will always appreciate a back link and a comment, though :)

Latest FileDrop release has been on 28th January 2012.

Download FileDrop – includes demo page, minified (filedrop-min.js) and full (filedrop.js) JavaScript files.

Please report problems and suggestions to the comments.

See also on-line demo page and FileDrop project on JSClasses.org.

Usage

Note: if you want to use the latest version you can hotlink to it using this URL (it will be backwards compatibile as much as possible):

http://proger.i-forge.net/filedrop-min.js

The following is the minimum required to use FileDrop:

xml<!DOCTYPE html>
<html>
  <head>
    <title>Basic FileDrop example</title>

    <script type="text/javascript" src="http://proger.i-forge.net/filedrop-min.js"></script>

    <style type="text/css">
    /* Essential FileDrop element configuration: */
    .fd-zone {
      position: relative;
      overflow: hidden;
      width: 15em;
      text-align: center;
    }

    /* Hides <input type="file" /> while simulating "Browse" button: */
    .fd-file {
      opacity: 0;
      font-size: 118px;
      position: absolute;
      right: 0;
      top: 0;
      z-index: 1;
      padding: 0;
      margin: 0;
      cursor: pointer;
      filter: alpha(opacity=0);
      font-family: sans-serif;
    }

    /* Provides visible feedback when use drags a file over the drop zone: */
    .fd-zone.over { border-color: maroon; }
    </style>
  </head>
  <body>
    <!-- A FileDrop area. Can contain any text or elements, or be empty.
         Can be of any HTML tag too, not necessary fieldset. -->
    <fieldset id="zone">
      <legend>Drop a file inside&hellip;</legend>
      <p>Or click here to <em>Browse</em>..</p>
    </fieldset>

    <script type="text/javascript">
      // Tell FileDrop we can deal with iframe uploads using this URL:
      var options = {iframe: {url: 'your-upload-script.php'}};
      // Attach FileDrop to an area:
      var zone = new FileDrop('zone', options);

      // Do something when a user chooses or drops a file:
      zone.on.send.push(function (files) {
        // if browser supports files[] will contain multiple items.
        for (var i = 0; i < files.length; i++) {
          files[i].SendTo('your-upload-script.php');
        }
      });
    </script>
  </body>
</html>

The above code creates a FileDrop xml<fieldset> area and sets it up so that it sends each chosen file to a server script (your-upload-script.php). It is self-sufficient and will work in any browser supported by FileDrop.

Download FileDrop | Demo | Page top. Don't forget to give feedback!

API

An entire FileDrop facility is contained in window.fd. In itself, FileDrop in itself is split into 2 classes: DropHandle and FileDrop, plus one File class. Apart from these there are global options and functions (belonging to window.fd instead of a particular FileDrop class).

FileDrop uses event-driven approach for better flexibility. See also CallOf() and CallAll() functions that call event chains (sets of callbacks).

Global options

Global options are set in window.fd:

logging
Boolean value toggling logging of debug messages to window.console. Logging is always disabled if there's no console support.
onObjCall
function (event, args), gets called before calling a chain of FileDrop events. this is set to the calling object.
  • This method is used on the demo page to log events called by FileDrop.

Global functions

AddEvent
Cross-browser event attachment.
ByID
Returns an element given its ID or, if passed argument is already a DOM element node (see IsTag) – that node itself.
CallAll
Calls handlers from given event chain event-driven system); if a handler returns non-null value all remaining handlers are skipped. Returns result value of the last invoked handler.
CallOf
A shortcut for calling event chain located in obj.on[event] object property; see it usages in FileDrop code to get the main idea.
ClassRegExp
Returns a RegExp object with pattern for detecting passed class name (for a DOM element).
Extend
Copies properties from one object to another; can optionally copy only undefined properties.
HasClass
Returns true if given DOM element has given class name.
InstanceOf
Returns name of instance function used to construct given object.
IsArray
Returns true if given object is a real Array.
IsTag
Returns true if passed argument is a proper DOM element node (note: not text node or other type), false otherwise.
NewXHR
Constructs a XMLHttpRequest object; supports IE 6 ActiveX.
RandomID
Returns a random node ID of form fd_ + random number between 1 and 9999. Doesn't check its uniqueness.
SetClass
Adds or removes class name of the given DOM node.
StopEvent
Stops propagation of the given event object.

Download FileDrop | Demo | Page top. Don't forget to give feedback!

DropHandle class

This is an abstraction layer that provides FileDrop class with normalized events occurring on file Drag & Drop and Browse. It creates xml<input type="file" /> and xml<iframe> elements and handlers their activity.

DropHandle doesn't do anything except handling node events – it doesn't change the appearence of zone or respond to Browse or Drag & Drop, it only invokes corresponding event handlers.

Constructor:

// zone - a DOM element or ID to hook file upload events for.
// opt - optional options, see below.
new fd.DropHandle(zone, opt);

Options:

fullDocDragDetect
A compatibility option that if set will cause Drag & Drop events to be detected document-wise rather than on given zone (currently only supported by Firefox). If unset this is autodected. Is always true for Google Chrome.
iframe
An object with xml<iframe> fallback settings. Currently has only one field (but FileDrop has more):
url
URL to point constructed xml<iframe> element to. Must be a server-side script that handles iframe upload.
inputClass
Class name to set to the constructed xml<input type="file" /> element.
zoneClass
Class name to add to passed zone.

Note: you can access passed zone element using zone property of the DropHandle class.

Download FileDrop | Demo | Page top. Don't forget to give feedback!

Events

Events are stored in on property, e.g. aDropHandle.on[dragEnter]. Each on member is an array of callbacks.

iframeDone
function (response). Occurs when an xml<iframe> upload has finished. response is the object returned by the server script plus several XMLHttpRequiest-like response properties making it suitable to use one callback function both for this and File's done event.
iframeSetup
function (iframe). Occurs when an xml<iframe> element was constructed and can be set up. Currently there's no default handler.
inputSetup
function (input). Occurs when a xml<input type="file" /> element was created and needs to be set up. Default handler adds opt.inputClass to it and sets its parent xml<form>'s style.position to relative to avoid overflow problem in Firefox 10 (it would still show the presumably hidden part of the input even outside the container bounds).
upload
function (e). Occurs when a file is dropped to zone. It happens in Firefox and Google Chrome because they support dropping files on xml<input type="file" />.
Drag & Drop

All handlers are of form function (e) where e is the native browser event object. Most useful events are dragEnter and dragLeave because others either don't work, are unstable or unclear.

For a detailed description of HTML 5 Drag & Drop events see this MozDev page.

dragEnd
Another drag & drop event that doesn't appear to be useful; see this page for description.
dragEnter
Occurs in supported browsers when a Drag & Drop event is received by zone (Firefox) or entire document (Chrome).
dragExit
Another drag & drop event that doesn't appear to be useful; see this page for description.
dragLeave
Occurs when Drag & Drop ends – e.g. the mouse pointer leaves zone or browser window.
dragOver
Another drag & drop event that doesn't appear to be useful; see this page for description.

Methods

Only methods of interest are listed here, others are easy to determine from the code.

AbortIFrame ()
Aborts file upload happening using xml<iframe>, if there was any happening.
Hook (node)
Initializes and attaches events to given node. Is called when constructing DropHandle.
Multiple ()
Returns true if the xml<input type="file"> element is configured for multiple file selection.
Multiple (Toggles)
Toggles multiple file selection of the xml<input type="file">. This affects «Browse» dialog popping up when user clicks on the drop zone (zone node DropHandle was constructed for).
PrepareInput (node)
Constructs required DOM elements (form, file input, iframe and others).
SendViaIFrame (url)
This method can be called to send a file using fallback xml<iframe> and xml<form> elements. It will prepare the form and set up the response handler that will call iframeDone event.

FileDrop class

This class provides the actual FileDrop features. It's based on DropHandle that gives a good degree of cross-browser abstraction. FileDrop uses DropHandle's events to respond to user actions and as such provides the same callbacks as that class.

Also, all DropHandle options, methods and other fields exist in FileDrop as well.

Constructor:

// zone - a DOM element or ID to hook file upload events for.
// opt - optional options, see below.
new fd.FileDrop(zone, opt);
// a global (window[]) alias exists - you should use it instead:
new FileDrop(zone, opt);

Options (see also DropHandle options):

dragOverClass
Class name to add to passed zone when a Drag & Drop session is active and a file is being hovered over zone (Firefox) or document (Chrome).
iframe
Adds one field to DropHandle's iframe:
force
If true, xml<iframe> upload will be forced even if browser supports AJAX upload using FileAPI or Chrome/Safari File false by default.

Note: you can access DropHandle object by handle property of the FileDrop class.

Download FileDrop | Demo | Page top. Don't forget to give feedback!

Events

Events are stored in on property, e.g. aFileDrop.on[send]. Each on member is an array of callbacks.

fileSetup
function (file). Occurs when a File object was constructed and can be set up. Currently there's no default handler.
send
function (files). Occurs when a set of files can be safely send – user agent supports some kind of FileAPI (of Firefox/, Chrome or Safari). An xml<iframe> upload can still be done when handling// this event using DropHandle SendViaIFrame(), if desired. Currently there's no default handler.

Methods

Only methods of interest are listed here, others are easy to determine from the code.

GetFilesFrom (e)
Is used by OnUpload() to convert native file upload event object to an array of browser-neutral File classes. Returns false if there's no FileAPI support.
OnUpload (e)
A default FileDrop handler for DropHandle's upload event. It either fires send event or initiates xml<iframe> upload if the browser doesn't support any FileAPI.

File class

Browser-independent abstraction layer for dealing with File objects of supported browsers (currenly Firefox/, Chrome and Safari). Wraps around native browser File// object that it's passed in the constructor.

It also provides a number of events wrapping around XMLHttpRequest (see SendTo() method).

Constructor:

// file - a native File object returned by the browser from an event object.
new fd.File(file);

File class has one option:

extraHeaders
If true (by default) will send 3 extra headers along with XMLHttpRequest when sent using SendTo(). Note: if you turn this off server script will have no information regarding file name and size when uploading them using Drag & Drop (AJAX).
  1. X-File-NameURL-encoded file name.
  2. X-File-Size – original file size.
  3. X-Requested-With – two values: FileDrop-XHR-FileAPI (for Firefox) and FileDrop-XHR-Chrome (for Google Chrome and Apple Safari).

File class has the following properties:

name
File name.
nativeFile
Native File object passed to File's constructor.
size
File size.
xhr
An instance of XMLHttpRequest that was last used to send the file by SendDo() or null if there was none.

Download FileDrop | Demo | Page top. Don't forget to give feedback!

Events

Events are stored in on property, e.g. aFile.on[error]. Each on member is an array of callbacks.

done
function (xhr, e). Occurs when the file has been uploaded (xhr.readyState == 4 && xhr.status == 200) and server response was received. Note: DropHandle provides callback for xml<iframe> upload – see SendViaIFrame() with simulated xhr structure.
error
function (e, xhr). There was an error while uploading the file or reading file binary data – in this case xhr parameter will be undefined.
progress
function (current, total, xhr, e) where current might be null if can't be determined; current and total are the number of bytes uploaded and total correspondingly.
readXHR
function (xhr, data) where data is an already read raw binary string. Occurs when a XMLHttpRequest object needs to be sent. Default handler (fd.File.SendXHR()) simply calls its sendAsBinary() or send() method, whichever is available.

Methods

Only methods of interest are listed here, others are easy to determine from the code.

Abort ()
Terminates last sent XMLHttpRequest request; does nothing if there was any (see also File's xhr property).
HookXHR (xhr)
Is used by SendTo() to attach event callbacks to the given XMLHttpRequest object.
SendTo (url)
Performs AJAX upload: reads file data, constructs and prepares a XMLHttpRequest object and sends read data to the server. Works in Firefox (using FileAPI), Google Chrome and Apple Safari. Calls error event on error and sendXHR when the request needs to be submitted.
  • Request is sent in POST mode and with application/octet-stream MIME/Content-Type. The latter is used to avoid encoding and other transformations done by some browsers (e.g. Firefox) when uploading text files.
  • Constructed XMLHttpRequest instance is stored in File's xhr property replacing previous if there was any.

Download FileDrop | Demo | Page top. Don't forget to give feedback!

Comments RSS20

Your name: Your homepage:

Text & signature markup:You can use UverseWiki markup. In short: **bold**, //italic//, %%code%%, ((URL link)), >inline quote, <[ multiline quote ]>.

Humans! Please enter "J" here: (or turn JavaScript on for automatic verification)
Subscribe by e-mail (manage):
Ctrl+Enter »