GithubHelp home page GithubHelp logo

burt202 / lite-uploader Goto Github PK

View Code? Open in Web Editor NEW
103.0 12.0 39.0 370 KB

Lightweight file uploader for NodeJS and jQuery with support for drag/drop, basic and custom validators and hooks for all the various events like progress etc

License: MIT License

JavaScript 98.97% PHP 0.58% HTML 0.45%

lite-uploader's Introduction

LiteUploader

npm license Build Status

Examples | Changelog

This is a lightweight library for NodeJS and jQuery, aiming to make uploading files a doddle. With some useful options including basic validation, it is a good choice for any developer who is not so worried about supporting legacy browsers.

Features

  • dependency free
  • file type and size validation
  • support for custom validators
  • hooks for all major events like progress, success, fail etc
  • drag/drop support
  • ability dynamically update the form data packet before each upload
  • upload multiple files as individual requests

NodeJS

npm install lite-uploader --save

Browser

<script src="./src/liteuploader.js"></script>

jQuery is supported but is optional

Options

Name Type Default Description
url String or Function (required) null url that will handle the upload, or a function that resolves with the url
ref String (required) null the request argument name for the file form data. Will fallback to the name property of the file input field if not supplied.
method String POST allows overriding of the default HTTP request method if necessary
rules Object {} object where you can specify validation rules for the files to be uploaded - current supported rules are:
  • allowedFileTypes (list of comma-separated mime-types, wildcards such as image/* are also supported)
  • maxSize (in bytes)
params Object {} object of params to be sent to the server in addition to the files being uploaded
headers Object {} object of headers to be sent to the server
validators Array [] an array of functions that can take a File and return a validation result on it, see examples for usage
singleFileUploads Boolean false set to true to upload each file of a selection using an individual request
withCredentials Boolean false indicates whether requests should be made using credentials such as cookies
beforeRequest Function null delay the file upload request by returning a promise. Recieves the Files and the FormData. Expected to resolve with the FormData to continue. Reject to stop upload.
sendAsFormData Boolean true when set to false and singleFileUploads is true, dont send the file payload as form data. Also any params added via 'addParam' to form data, will be ignored

Events

Name Parameters Description
lu:errors eventName, {errors} triggered when errors are found, including built-in and custom validators - see 'Error Types' section for more
lu:start eventName, {files} triggered before any uploading starts
lu:finish eventName triggered when all uploading has finished
lu:before eventName, {files} triggered before each request to the server
lu:progress eventName, {files, percentage} triggered whilst uploading files
lu:success eventName, {files, response} triggered on a successful request to the server
lu:fail eventName, {xhr} triggered on a failed request to the server
lu:cancelled eventName triggered on upload abort

Error Types

Below is an overview of the built-in error types that can be returned when validating files

  • type - when file mime type does not match any mime types supplied in the rule.allowedFileTypes option
  • size - when file size is above the size (in bytes) supplied in the rule.maxSize option
  • refRequired - when there is no name attribute on the file input and no 'ref' options is passed to the plugin
  • urlRequired - when no 'url' option is passed to the plugin

Public API

startUpload(files)

Starts the upload

Name Type Default Description
files FileList (optional) null a list of files to be uploaded, takes priority over default mechanism if supplied

addParam(key, value)

Allows parameters to be added after plugin instantiation

Name Type Default Description
key String (required) n/a name of parameter to be added
value String (required) n/a value of parameter to be added

cancelUpload()

Allows the upload to be cancelled, triggers lu:cancelled

Name Type Default Description
No parameters

Browser Support

  • Chrome 45+
  • Firefox 34+
  • Edge 12+
  • Internet Explorer NO (because Promises and Object.assign are used)
  • Safari 9+
  • Opera 32+

License

Licensed under the MIT License.

View the full license here.

lite-uploader's People

Contributors

burt202 avatar malthe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lite-uploader's Issues

How to use input values as uploader params?

I want to upload file and attach some variables by $_POST ex.:

$('#ajaxUploaderInput').liteUploader({
'params': {
'category': $('select[name="file_category').val()
}
});

The data in 'params' is collected when I init .liteUploader(). Is it possible to do what I need?

logo proposal

Hi, @burt202 am a graphics designer. I will like to know if you want me to create a logo for your project.

lu:succes response type proposal (if return JSON)

Hi

When return data as JSON lu:success event gives an error because of "double quotes".

_onXHRResponse: function(files, xhr) {
    if (xhr.readyState !== 4) return;

    this._triggerEvent("lu:finish");

    if (xhr.status >= 200 && xhr.status < 300) {
        this._triggerEvent("lu:success", { files, response: xhr.responseText });
    } else {
        this._triggerEvent("lu:fail", { xhr });
    }
},

So i change code
xhr.responseText

to

(function(raw) { try { return JSON.parse(raw); } catch (err) { return e.responseText;} })(e.responseText)

and running perfectly. FYI

_onXHRResponse: function(files, xhr) {
    if (xhr.readyState !== 4) return;

    this._triggerEvent("lu:finish");

    if (xhr.status >= 200 && xhr.status < 300) {
        this._triggerEvent("lu:success", { files, response: (function(raw) { try { return JSON.parse(raw); } catch (err) { return e.responseText;} })(e.responseText) });
    } else {
        this._triggerEvent("lu:fail", { xhr });
    }
},

IE10/11

What feature make this lib not supporting IE10/11

Upload On Change

is it possible to upload without having a selector?

<input type="file" id="uploader" onchange="return uploading()">

<script>
function uploading() {
  $(this).liteUploader({
      // options
  }); 
  or
  $.liteUploader({
      // options
  });
}
</script>

Add access to XMLHttpRequest.abort()

Javascript is the only language I sometimes try to work with without understanding it, but to me it looks like the XMLHttpRequest is encapsulated in _performUpload and not really accessable to the user.

I would like to be able to cancel an upload in progress by calling XMLHttpRequest.abort(), preferably by calling a method on the uploader.

I could fork your project, modify it and create a pull request, but I don't think you (or anybody else) would be thrilled with the quality of my javascript code.

Error: ".done is not a function" from returned Promise.resolve(formData)

The Promise object does not have a done(), but rather a then(). Replacing done() with then() resolves the issue.

Just a note, it seems the JS Promise is not supported in IE11 (and IE11 still has big usage), maybe consider returning to the jQuery promise methods.

Either way, wonderful library. I will continue to use.

Thanks,
Scott (keenlinks)

Progress bar shoots to 100%

I am using the following code to create a progress bar:

.on('lu:progress', function (e, percentage) {
$('#progbar').css(
'width',
percentage + '%'
);})

However the bar shoots to 100% and sits there until the upload completes.

This happens on all browsers on Windows 8.1 but works on all Mac OS X Mavericks browsers. I understand this may be a browser or OS issue.

Share a file style

I'm very like this project, it's simple and powerful , easy to use, in my case, I need to bind a #ID dom to upload, and make the file input looks beautiful. so I find the solution, I think other people will need too

<a href="javascript:;" class="file">选择文件
      <input type="file" name="uploadfile" class="liteupload" multiple="multiple">
</a>

<style media="screen">
        .file {
            position: relative;
            display: inline-block;
            background: #D0EEFF;
            border: 1px solid #99D3F5;
            border-radius: 4px;
            padding: 4px 12px;
            overflow: hidden;
            color: #1E88C7;
            text-decoration: none;
            text-indent: 0;
            line-height: 20px;
        }
        .file input {
            position: absolute;
            font-size: 100px;
            right: 0;
            top: 0;
            opacity: 0;
        }
        .file:hover {
            background: #AADFFD;
            border-color: #78C3F3;
            color: #004974;
            text-decoration: none;
        }
</style>

<script src="/theme/hunter/js/liteuploader.js"> </script>
<script>
  $(".liteupload").liteUploader({
    script: "/public/safe/upload?safe_key=6kUxOb",
    params: {
      foo: "bar",
      abc: 123
    }
  })
  .on("lu:success", function (e, response) {
    document.getElementById('fujian').value = response.data.full_path_new_name;
  });

  $(".liteupload").change(function () {
    $(this).data("liteUploader").startUpload();
  });
</script>

Webpack Error

I ve got this error when using webpack to compile the scripts.

jQuery.Deferred exception: $(...).liteUploader is not a function TypeError: $(...).liteUploader is not a function

i am using Laravel mix autoload to load $ jquery as global variable, settings. Any idea?
https://github.com/JeffreyWay/laravel-mix/blob/master/docs/autoloading.md

Adding the UMD module support code, fixed the problem.

if (typeof define === 'function' && define.amd) {
  define(['jquery'], factory);
} 

Multiple file upload not working

Hello,

With the following setup

file_obj = $('#files');
file_obj.liteUploader({
script: "/upload",
rules: {
allowedFileTypes: "application/pdf",
maxSize: 100*1024*1024,
}
})
file_obj.change(function () {
$(this).data("liteUploader").startUpload();
});

and this html input:

<input type="file" name="files" multiple id="files" required="True"/>

it still continue to upload just the first file.
In the serverside script (which is in python: I am using OpenERP/Odoo), I see there's only one file as well.
I also tried to set singleFileUploads to true, but still the server is called once.

Node App Error

I tried the 'node without jquery' example.

var LiteUploader = require("lite-uploader");

var options = {script: "test.php"};  // takes all of the documented options
var getFiles = function () {
  // return a FileList
};
var onEvent = function (name, value) {
  // called on all documented events
};

var liteUploader = new LiteUploader(options, getFiles, onEvent)

It throws error like, TypeError: LiteUploader is not a constructor

@burt202 Any idea?

Sequencial upload with singleFileUploads

When singleFileUploads mode is used, as it's desired, each multi-part request has only one payload. But the requests are done in parallel without any limit (queueing)! Considering the progress, you can't tell easily on what file the progress is reported. I've extepcted that this mode sends file one-by-one.

Evevnt on all files upload

singleFileUploads - true
I can not figure out how to make the event after the upload of all the files ?

Webpack Error

Im using Laravel Elixir Webpack to compile all the javascript libraries and scripts.

They are all fine except, i keep getting the error.

Any advise on how to fix it?

php app.js?8b67:146 Uncaught TypeError: $(...).liteUploader is not a function(…)

webpack

CSS Theme?

Hi friend,

Excellent repo! I don't know why, but is the only one that work on my hosting.

How can I format a progress bar?
I don't understand why the example gave me different lines to the upload progress.

Best regards,

Internet Explorer

Is there any compatibility issue with Internet Explorer?

i was testing it in IE11, it doesn't give me any warning or error at all.

It works great on any other browsers though!

$('#uploader').liteUploader({
 script: 'dialog/',
 rules: {
   maxSize: 31457280
  },
   params: { form: 'upload', file_type: 'video' }
})
.on('lu:errors', function (e, errors) {
   var is_error = false;
   $.each(errors, function (i, error) {
     if (error.errors.length > 0) {
         alert('Maximum 30MB video') // No alert in Internet Explorer
     }
    });
})
.on('lu:success', function (e, errors) {
   $('#uploader').liteUploader().off();
});

Please note: it does sometimes works. the first click, browse dialog open but wont upload, but then second click then it works.

Video Format

Does it support video format?
it return empty when i print_r($_FILES)

Only one file included in "errors" variable inside lu:errors

Before I could iterate over the errors variable like this:

var html = "<ul>";
$.each(errors, function (key, value) {
    html += "<li>" + value.name + ": ";

    $.each(value.errors, function (i, err) {
        html += lang["FILEUPLOAD_MESSAGES"][err.type.toUpperCase()];

        // append <br /> if necessary
        html += i == value.errors.length - 1 ? "" : "<br />";
    });
});
html += "</ul>";

Now with the most recent version I can't anymore.

If I console.log my errors variable I get to see this:
({name:"Foto0928.jpg", errors:[{type:"size", rule:200000, given:338968}]})

I don't get that. Even if I select multiple files, I only get one file included in that "object".
What's even weirder is that I'm wondering why this object has curved brackets around it. I thought it'd be just a plain object?

Either way I'm doing something wrong or there's a bug in this library.

Thanks.

Why do you put an [] to the input's name?

I'm not 100% sure, but you add "[]" to the end of the name of an input. I think you shouldn't do this. This is special to php and maybe some langauges for multiple files, but this should be always already done in HTML.

With this name changing code, the upload might only work with JS enabled, but never if JS is disabled. Which means you want the developer to write wrong HTML to get the job done. Consider what happens, if a devloper uses the "right" HTML:

<input type="file" name="files[]" multiple="" />

Unexpected token F

I keep getting that error in my firebug console and it doesnt recognise the parameter.

any idea, why?

<input type="file" name="uploader" id="uploader" class="textinput">
$(function(){
    $('#uploader').liteUploader({
        script: '//'+window.location.host+'/script/php/html/system',
        params: { form: 'upload3', section: 'settings|:|product' },
        rules: {
            maxSize : '1048576', 
            allowedFileTypes: 'image/png,image/jpeg,image/gif'
        }
    })
});

Uploaded Images are flipping

Hey. I'm a longtime fan of your beautiful file loader. But faced with the problem: in Mac OS uploaded images are flipping. Only the OS X and iOS. Thank you.

Simple support for drag and drop and paste uploads.

Pre v2.3.0 it was easy enough to implement a past or drag'n drop upload. It was just another listener in the _init call.
But now with the _init gone and the getFiles and trigger passed to the LiteUploader I'm not sure how to approach this.

@burt202 Any advice how to proceed on this, to fit your architecture?

How i list errors?

Hi.

How i can put a alert when the user uploads a different supported type file?

$('#file-upload').liteUploader(
{
script: '{{ url('profile/image/upload') }}',
rules: {allowedFileTypes: 'image/jpeg,image/png,image/gif', maxSize: 2097152},
})
.on('lu:errors', function (e, errors) {
$.each(errors, function(i, error) {
alert(error.rule);
});

})

Thanks (i'm new in github)

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.