Coder Social home page Coder Social logo

upload.js's Introduction

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.

upload.js's People

Contributors

georgelee1 avatar

Stargazers

 avatar Ewerton Dutra avatar Francisco Brito avatar Eli Alejandro avatar Lau Borges avatar

Watchers

James Cloos avatar  avatar

Forkers

totang2

upload.js's Issues

Show file name

At the moment the only way for the user to be able to distinguish between two different files is by the preview thumb in the widget. There should be an option to toggle whether or not to show the name of the file overlaid on the preview thumb, by default this should be false. The option values should allow the file name to appear when the mouse is hovered over the item or always.

Ability to send additional parameters

On upload and delete have the ability to send additional parameters in addition to the standard file parameter.

Can be set through options via JS under upload.additionaParams. Should return object or function that returns an object, or through data html attributes in the format data-upload-additional-param-<key>=<value>

Drag and drop

Implement drap and drop upload using the HTML5 Drag and Drop API. Icon of the add button should change to something more suitable and possible text added to inform user of drag and drop and click to select abilities.

UploadJs support gracefully handle browsers that do not support the HTML drap and drop API.

Syntax error in options for http

Please explain the upload handler a bit in your README. I'm trying to use your plugin but my JS is crashing saying url is not defined.

Non ajax support

For some developers it is not desired to have the upload done asynchronously using AJAX, instead they want the image uploads added to the current form so that are included in the form submit.

This change will involving adding a new option where by the functionality will be to add hidden input[type=file] elements when adding new files. For deletion, files that have just been added can simply remove the newly created input[type=file] element, for existing an new input[type=hidden] element should be added with the name from the data-delete-param value and the value from the upload-image-id.

The readme documentation should also be updated with the new option.

Graceful support for older browsers

For browsers that do not support the HTML5 file or formdata API UploadJs should gracefully fall back to the functionality to be implemented in issue #3.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.