Skip to content

A simple and clean HTML5, dependency free, image uploader and remover

License

Notifications You must be signed in to change notification settings

georgelee1/Upload.js

Repository files navigation

Upload.js

A simple and clean HTML5, dependency free, image uploader and remover


Contents


See Upload.js in action


Install

Download The latest release of Upload.js and add it to your project

<head>
   <link rel="stylesheet" href="path/to/css/uploadjs.css" />
</head>
<body>
   ...
   <script src="path/to/js/uploadjs.js"></script>
</body>

or

Install via the Bower package manager and add it to your project

bower install uploadjs
<head>
   <link rel="stylesheet" href="bower_components/uploadjs/dist/uploadjs.css" />
</head>
<body>
   ...
   <script src="bower_components/uploadjs/dist/uploadjs.js"></script>
</body>

Dependencies

None, zero, zilch, zip, nadda

This project is designed to be standalone. We don't force your project to have to include any other third party libraries.


Browser Support

Any browser that supports HTML5, XMLHttpRequest advanced features and File/FileReader API.

  • Chrome (28+)
  • Firefox (38+)
  • IE (10+)
  • Safari (6.0.2+)

Usage

Pretty simple really add a div to your page, find it in your script and call the UploadJs plugin.

html

<div id="my-uploadjs"></div>

javascript

var myDiv = document.getElementById("my-uploadjs")
new UploadJs(myDiv)

Initial Images

It is possible to show initial images in the widget that may previously exist. Simply include them as img tags within the div. If you are enabling deletable each img tag must include the HTML data attribute data-upload-image-id=<id> where <id> is a unique identifier for the file that will be set as the deletion parameter to the deletion URL.

<div id="my-uploadjs"></div>
   <img src="my-img-1.jpg" data-upload-image-id="1" />
   <img src="my-img-2.jpg" data-upload-image-id="2" />
</div>

Options

UploadJs is configurable in it's behaviour. All options are configurable via the javascript options, and many others as HTML data attributes. You can use a combination of the two where applicable.

Via javascipt

var options = {
   upload: {
      url: "/upload"
   },
   delete: {
      url: "/delete"
   }
}
new UploadJs(myDiv, options)

Via html data attributes

<div id="my-uploadjs" data-upload-url="/upload" data-upload-delete-url="/delete" />

Available Options

Name Option Description
Upload Url
upload: { url: <string> }
or
data-upload-url="<string>"
The URL that is called when uploading a file. The url must return JSON with success: true if the upload was successful and with uploadImageId: <id> where <id> is a unique identifier for the file that will then get called to the deletion URL. If uploadImageId is not returned the uploaded file will not be deletable from the widget.
Upload Parameter
upload: { param: <string> }
or
data-upload-param="<string>"
Default:'file'

The name of the parameter that each file is set as in the upload request.
Deletion Url
delete: { url: <string> }
or
data-upload-delete-url="<string>"
The URL that is called when deleting a file. The url must return JSON with success: true if the deletion was successful.
Deletion Parameter
delete: { param: <string> }
or
data-upload-delete-param="<string>"
Default:'file'

The name of the parameter set with the file id that is set on the deletion request.
Max
max: <int>
or
data-upload-max="<int>"
Default:infinite

The maximum number of files that are allowed to exist in the widget.
Deletable
deletable: <boolean>
or
data-upload-deletable="<boolean>"
Default:true

Indicates whether or not files are deletable. If true the delete button will appear for each file, when clicked the deletion url is called.
Allowed Types
allowed_types: []
or
data-upload-allowed-types="<string>[,<string>[,...]]"
Default:["images"]

<array> or commor (,) separated <string> of allowed file MIME content types e.g. image/png, image/jpg. You can use the predefined type key images which includes ["image/jpg", "image/jpeg", "image/png", "image/gif"] e.g. allowed_types: ["images"].

Callback

When defining the options via the javascript API, option values can be defined using a function. There is an optional done callback that can be passed to the options function that should be called, passing the option value, when the option value has been loaded. If the done callback is not defined as a function parameter then the option value should be returned.

Option defined as function without callback

var uploadUrl = ...
var options = {
    upload: {
       url: function() {
          return uploadUrl;
       }
    }
}

Option defined as function with callback

var uploadUrl = ...
var options = {
    upload: {
       url: function(done) {
          done(uploadUrl);
       }
    }
}

Http Additional Parameters and Headers

It is possible to define additional parameters and headers to be included in the upload and delete http calls. These parameters/headers can be defined statically or can be dynamic. Static definition is done using html data-upload-additional-param-<key> or data-upload-delete-additional-param-<key> or data-upload-header-<key> or data-upload-delete-header-<key> attributes or via the javascript options, note that when using a combination of the two javascript values with take presendence of the html attributes.

Html definition

<div id="my-uploadjs" 
     data-upload-additional-param-my-param="myValue"
     data-upload-additional-param-other-param="anotherValue" 
     data-upload-delete-additional-param-del-param="deleting" 
     data-upload-header-testheader="headerValue" 
     data-upload-delete-header-delheader="delHeaderValue" />

Javascript definition

var options = {
    upload: {
        additionalParams: {
            myParam: "myValue",
            otherParam: "anotherValue"
        },
        headers: {
            testheader: "headerValue"
        }
    },
    delete: {
        additionalParams: {
            delParam: "deleting"
        },
        headers: {
            delheader: "delHeaderValue"
        }
    }
}

You can take advantage of the callback functionality for options to create the additional parameters dynamically. An object of the parameters must be returned from the function or passed to the done callback if defined (see callback functionality).

var options = {
    upload: {
        additionalParams: function() {
            var my = "my";
            var value = "Value";
            
            return {
                myParam: my + value,
                otherParam: "anotherValue"
            }
        }
    },
    delete: {
        additionalParams: function(done) {
            done({
                delParam: "deleting"
            });
        }
    }
}

These examples will add myParam=myValue and otherParam=anotherValue to the upload http request and delParam=deleting to the delete http request in addition to the standard file parameters. In additional the http header of testheader: headerValue will be added to the upload and delheader: delHeaderValue to the delete http request.

HTML Data Attributes and Case

When using HTML data-* attributes be aware of how browsers will parse the attribute value, see HTMLElement.dataset for full details. If you define an attribute data-upload-header-X-MYHEADER="test" the header will come out as XMyheader: test.

If case is important in your parameters or headers then you should define them using the JS options.

var options = {
    upload: {
        headers: {
            "X-MYHEADER": "test"
        }
    }
}

Methods

Methods available on UploadJs and what they are good for

Method Description Usage
on(<string>, <function>) Adds a listener to UploadJs that will trigger the passed function for the event. Available events are:

  • upload.added - A new file upload has been added to the queue for upload
  • upload.started - The file upload has been taken from the queue and actual upload has stared
  • upload.progress - Fired with with the progress of the upload
  • upload.done - The upload has successfully completed with success from the server
  • upload.fail - The upload of the file failed
  • delete.added - An existing file has been added to the queue for deletion
  • delete.started - The file deletion has been taken from the queue and the request to server is being made
  • delete.done - The file was successfully deleted
  • delete.failed - The file deletion failed


The event object is passed to the handler function. It contains the following field:
  • type - the event type
  • file - field present for upload.* events, a reference to the file object.
  • id - field present for delete.* events, the file id
  • progress - int field 0-100 present for upload.progress event
var uploadJs = new UploadJs(...);
uploadJs.on("upload.done", function(e) { ... });
destroy() Destroys the UploadJs widget, cleaning up all resources and removes all DOM elements. Note that any uploading files will continue to upload until they are complete, but any queued uploads/deletions will be cancelled immediately. var uploadJs = new UploadJs(...);
uploadJs.destroy();

Styling

By default the icons used in UploadJs are unicode symbol characters

✓ ⇡ ✘ !

These can be changed to make the widget look a little nicer by using icons from either font-awesome or glyphicons. Simply add the appropriate css class to the div element. Checkout the demo to see these in action.

font awesome

<div id="my-uploadjs" class="up-fa"></div>

glyphicons

<div id="my-uploadjs" class="up-glyphicons"></div>

Issues and Contributing

If you have found a bug or would like a new feature added to UploadJs or you would just like to contribute then please read the Contributing read me before anything else.