Giter Site home page Giter Site logo

danielm / uploader Goto Github PK

View Code? Open in Web Editor NEW
1.2K 75.0 389.0 151 KB

A lightweight and very configurable jQuery plugin for file uploading using ajax(a sync); includes support for queues, progress tracking and drag and drop.

Home Page: https://danielmg.org/demo/java-script/uploader

License: MIT License

JavaScript 96.33% CSS 3.67%
javascript jquery lightweight upload ajax forms file widget multiple dnd drag drop progress queue jquery-plugin

uploader's Introduction

jQuery Ajax File Uploader Widget

A jQuery plugin for file uploading using ajax(a sync); includes support for queues, progress tracking and drag and drop.

Very configurable and easy to adapt to any Frontend design, and very easy to work along side any backend logic.

The focus will be modern browsers, but also providing a method to know when the plugin is not supported. The idea is to keep it simple and lightweight.

Basic Javascript knowledge is necessary to setup this plugin: how to set settings, callback events, etc.

  • Lightweight: ~8.00 KB
  • Dependencies: just jQuery!
  • License: Released under the MIT license

Build Status npm version Bower version

Live DEMOS

Check the live Demos here: https://danielmg.org/demo/java-script/uploader

Table of contents

Installation

NPM

npm install dm-file-uploader --save

Bower

bower install dm-file-uploader --save

Download tarball

You can download the latest release tarball directly from releases

Git

git clone https://github.com/danielm/uploader.git

Migration from v0.x.x

1.x.x got a lot of changes and new features, if you are a previous version user read CHANGELOG.md, there you can find the specific details of what was changed or removed.

Usage

As shown in the demos there are many ways to use the plugin, but the basic concepts are:

  • Initialize the plugin on any HTML element such as: <div /> to provide a Drag and drop area.
  • All <input type="file"/> inside the main area element will be bound too.
  • Optionally you can bind it directly to the <input />

Example Markup

This is the simple html markup. The file input is optional but it provides an alternative way to select files for the user(check the online demo to se how to hide/style it)

<div id="drop-area">
  <h3>Drag and Drop Files Here<h3/>
  <input type="file" title="Click to add Files">
</div>

Initialization

   <script src="/path/to/jquery.dm-uploader.min.js"></script>
$("#drop-area").dmUploader({
  url: '/path/to/backend/upload.asp',
  //... More settings here...
  
  onInit: function(){
    console.log('Callback: Plugin initialized');
  }
  
  // ... More callbacks
});

Down below there is a detailed list of all available Options and Callbacks.

Additionally, after initialization you can use any of the available Methods to interact with the plugin.

Options

  • queue: (boolean) Default true Files will upload one by one.

  • auto: (boolean) Default true Files will start uploading right after they are added. If using the queue system this option means the queue will start automatically after the first file is added.

    Setting this to false will require you to manually start the uploads using the API Methods.

  • dnd: (boolean) Default true Enables Drag and Drop.

  • hookDocument: (boolean) Default true Disables dropping files on $(document).

    This is necessary to prevent the Browser from redirecting when dropping files.

    The only reason why you may want to disable it is when using multiple instances of the plugin. If that's the case you only need to use it once.

  • multiple: (boolean) Default true Allows the user to select or drop multiple files at the same time.

  • url: (string) Default document.URL Server URL to handle file uploads (backend logic).

  • method: (string) Default POST HTTP method used by the upload request.

  • extraData: (object/function) Collection of parameters to add in the upload request.

    // Example
    extraData: {
       "galleryid": 666
    }

    If you need a dynamic value this can be set as a function. Also, if this function returns false nothing will be added.

    // Example
    extraData: function() {
       return {
         "galleryid": $('#gallery').val()
       };
    }
  • headers: (object) Collection of headers to send in the upload request.

    // Example
    headers: {
       'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
  • dataType: (string) Default null Response type of the upload request.

    Default is null which means jQuery will try to 'guess' depending of what the server returns.

    Other values can be: xml, json, script, html or text

    Reference: http://api.jquery.com/jquery.ajax/

  • fieldName: (string) Default 'file' Field name in the upload request where we 'attach' the file.

    // For example in PHP if using the default value you can access the file by using:
    var_dump($_FILES['file']);
    // 'file' correspond to the value of this option.
  • maxFileSize: (integer) Default 0 File validation: Max file size in bytes. Zero means no limit.

    maxFileSize: 3000000 // 3 Megs
  • allowedTypes: (string) Default "*" File validation: Regular expression to match file mime-type.

    allowedTypes: "image/*"
  • extFilter: (array) Default null File validation: Array of allowed extensions.

    extFilter: ["jpg", "jpeg", "png", "gif"]

Callbacks

General purpose

  • onInit: () Widget it's ready to use.

  • onFallbackMode: () Triggers only when the browser is not supported by the plugin.

  • onDragEnter: () User is dragging files over the drop Area.

  • onDragLeave: () User left the drop Area.

    This also triggers when the files are dropped.

  • onDocumentDragEnter: () User is dragging files anywhere over the $(document)

  • onDocumentDragLeave: () User left the $(document) area.

    This also triggers when the files are dropped.

  • onComplete: () All pending files are completed.

    Only applies when using queue: true. See options.

    Triggers when the queue reaches the end (even if some files were cancelled or gave any error).

File callbacks

All these include id

id (string): Unique ID. Useful to identify the same file in subsequent callbacks.

  • onNewFile: (id, file) A new file was selected or dropped by the user.

    • file (object): File object, use it to access file details such as name, size, etc.

      For reference click here.

    • If multiple are added, this gets called multiple times.

    • File validations were already executed.

    • If a return value is provided and is === false the file will be ignored by the widget.

    • Use this return value to implement your own validators.

  • onBeforeUpload: (id) Upload request is about to be executed.

  • onUploadProgress: (id, percent) Got a new upload percentage for the file

    percent (integer) : 0-100

  • onUploadSuccess: (id, data) File was successfully uploaded and got a response form the server

    data (object) : Upload request response. The object type of this parameter depends of: dataType

    See more in options.

  • onUploadError: (id, xhr, status, errorThrown) An error happened during the upload request.

    xhr (object) : XMLHttpRequest

    status (integer) : Error type, example: "timeout", "error", "abort", and "parsererror"

    errorThrown (string) : Only when an HTTP error occurs: Not Found, Bad Request, etc.

    Reference: http://api.jquery.com/jquery.ajax/

  • onUploadComplete: (id) The upload of the file was complete.

    This triggers right after onUploadSuccess or onUploadError. In both cases.

  • onUploadCanceled: (id) Upload was cancelled by the user.

    This one triggers when cancelling an upload using one of the API methods.

    See more in methods.

Validation callbacks

  • onFileTypeError: (file) File type validation failed.

    Triggers when using the setting: allowedTypes.

    See more in options.

  • onFileSizeError: (file) File size validation failed.

    Triggers when using the setting: maxFileSize.

    See more in options.

  • onFileExtError: (file) File extension validation failed.

    Triggers when using the setting: extFilter.

    See more in options.

Methods

There are a few methods you can use to interact with the widget, some of their behavior may depend on settings.

  • start: (id) Start the upload. (id is optional)

    Depending on the situation this method may do:

    • Start the upload of an individual file if an id was provided and there isn't a queue running.
    • Retry a failed or a previously cancelled file.
    • Start the queue if auto is set to false and no id is provided
    • Start ALL the pending files if queue is set to false false

    Example:

    $("#drop-area").dmUploader("start", id);
  • cancel: (id) Cancel the upload. (id is optional)

    Depending on the situation this method may do:

    • Cancel a file that is currently uploading if an id is provided.
    • Cancel all currently uploading files if an id is NOT provided.
    • Cancel a pending file, and it it will be skipped by the queue if using that option
    • Stop the current queue if using that option, and all current uploads.

    Example:

    $("#drop-area").dmUploader("cancel", id);
  • reset: () Resets the plugin

    • Stops all uploads
    • Removes all files
    • Resets queue

    Example:

    $("#drop-area").dmUploader("reset");
  • destroy: () Destroys all plugin data

    • Stops all uploads
    • Removes all files
    • Releases all the events, including the ones used by hookDocument if using that option

    Example:

    // Example
    $("#drop-area").dmUploader("destroy");

uploader's People

Contributors

bryant1410 avatar danielm avatar dellert avatar kauegimenes avatar naprstek avatar orthographic-pedant avatar voidabhi 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  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

uploader's Issues

Ajax error 500, Internal Server Error

I'm stuck with this error, i know what type of error is. The problem is that the error occur only for some files i upload, for others i get response 200 and i'm trying to figure out why this happens.
screenshot

Demo needed!

I have a kind of special use case where I need to allow only just one upload. I have read the docs but I do not see a maxFile (or something that looks like it) option.

I also need to allow users cancel an ongoing upload (this is provided in the demo) or delete the file entirely if upload has finished (there is a mention of this in the docs but no demo on how to implement).

Thank you

Reset queue.length ?

Looking for a way to reset queue.length, i.e. want only 1 upload but allow user to reset / re-upload an image without reloading the script.

Any ideas how to do this?

Not an issue, sorry for listing this question here. I guess you could call it a feature-request :)

Reset queue

Hi,
I have a scenario like, I will choose the files and maxFile limit is 4.
I am giving the delete icon to delete uploaded file.
Now consider I have uploaded 2 images so now remaining count is 2.
And if I delete 1 then remaining count should be 3.

But I couldn't reset the queue back.
Can you please help me with this.

Thanks in advance.

what different about allowedTypes and extFilter?

when I settings:

allowedTypes: 'image\/jpeg|bmp|jpg|png',
extFilter: 'jpg;png;bmp',

but the image of jpeg doesn't upload;

then I settings:

allowedTypes: 'image\/jpeg|bmp|jpg|png',
extFilter: 'jpg;png;bmp;jpeg',

the image of jpeg has upload;

then I remove extFilter settings, the image of jpeg also has upload.

so, I want to know, what different about allowedTypes and extFilter?

Missing semicolon in the minified file

The minified file, dmuploader.min.js is missing the semicolon from the end of the line.

Then if you have this uploader anywhere else in your javascript file than last library (set by a Javascript-minifier / library-concatenator) the whole thing will fail, as a browser thinks this library is a function taking the next library as an argument.

Luckily the fix is very easy.

Composer install

I see you can use Brower, Can you use Composer. I use it to install jquery and jquery-ui?

Thanks

Ken

Upload to my desire path

Hi,
Thank you for this plugin awesome.

I set url: upload.php now what to do then? how to upload the images to the desired path.
Can you give me sample upload.php

Please help me.

Thank You

onNewFile called on UploadError

Great tool Daniel. Thank you for this. I'm having a problem; for some reason, the onNewFile is called even when there is an upload error returned from the XHR call. I've implemented the image preview - and it's showing the preview for images my server-side script is rejecting.

Any ideas?

Token Mismatch With Laravel

I switched from dropzone to this and I like it, however I thuoght I could manipulate the ajax data sending how I wanted, which seems to not be true.

Laravel forms need a csrf token to be verified.

Although I have it in my form, I still did get the 'tokenMisMatch' error, which made me conclude that this plugin does send only files input...

How do I manipulate the request to take all of the forms input, and send it onclick, and autoqueued as is here by default?

I believe it is via the extraData option... but how?

Cursor remains in "loading" state

dmuploader all works fine, thanks for that!

The only issue i am confronted with is that the cursor won't go back to its normal (default) state when the upload is finished. (Occurs only in Opera)
Does anyone have a quick fix for that?

extraData dont change on fly

I found that parameter "extraData" dont update itself.
(extraData takes only first value, if I change value in select box it does not update)

For example:

$("#drag-and-drop-zone").dmUploader({
url: '/admins/modules/gallery/new_image.php?gallery='+gallery_id,
dataType: 'json',
fileName: 'files',
allowedTypes: 'image/*',
extFilter: 'jpg;png;gif',
extraData: {
gallery: $('#gallery_id option:seletced').val()
},
..........

upload goes on if onBeforeUpload returns false

the minified file doesn't return if onBeforeUpload returns false

these lines are forgotten in the minified version

var can_continue = widget.settings.onBeforeUpload.call(widget.element, widget.queuePos);
    
    // If the client function doesn't return FALSE then continue
    if( false === can_continue ) {
      return;
    }

cancel upload image

hi, thanks for your work.
Is it possible to cancel uploading file before success or error ?
thnx

Drag and drop

hi i downloaded uploader-master.
When i drag and drop the image on google chrome for demo / index.html Nothing happened. Do i need to run wamp php server or change index.html to index.php.

Thank you

Set extraData just before upload

hi, thanks for your work.

Is it possible to set extraData just before upload? Like this

$('#dmuploader-div').dmUploader({
    onBeforeUpload: function() {
        $(this).extraData = {someField: $('#some-input').val()};    
    }
})

Parse error

Hello,

I'm trying to use your uploader, but I have a problem. I get it to show and work as long as I don't put anything more in the upload.php . Once I put my php code for uploading in it, it gives the following error:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I use the following code to upload the (multiple) files to the server:

$dir = 'test/';
if(is_uploaded_file($_FILES['files']['tmp_name'])){
$file = $_FILES['files']['name'];
if(move_uploaded_file($_FILES['files']['tmp_name'], $dir.$file))
{
echo json_encode(array('status' => 'ok'));
}
else
{
}
}

Do you know how to fix this error?

POST All queued files as one job

I am trying to have my implementation of the plugin send all queued files to my controller action at one time. Is there an option to do this natively with this plugin?

I tried setting the queue to false, but this sends all the files in parallel, rather than as one post action.

Several <input on one page

Hello! Is it possible to make it works with several inputs on one page?
I tried it, but uploader works only with first input ob the page.

Legacy branch?

Hi!

I did use this (commit 125c502 ) both src/dmuploader.min.js and demos/js/demo-preview.js

Since then, it seems that there is a lot of development going on, and the API has changed, so that the upgrade is not straight forward?

So I was hoping could you create a maintenance-branch for the legacy version, just before the API changed?

in your README file has a error

onUploadProgress:

onUploadProgress: function(id, percent){
console.log('Upload of #' + id ' is at %' + percent);
// do something cool here!
}

it's error

-------------------" + here " ----------------

onUploadProgress: function(id, percent){
console.log('Upload of #' + id + ' is at %' + percent);
// do something cool here!
}

Files not uploading

Hi,

I am using uploader installed with npm. Uploader gets initiated properly (onInit callback fires). When I choose file - onNewFile callback fires. But nothing else gets fired. File is not being uploaded. No errors (I hooked all possible callbacks) and file not getting sent :/

In different project, where I use uploader installed manually by including .js files - it's working great.

Any ideas what I am doing wrong? :(
https://pastebin.com/UqqY1CwC

Limit queue to 1 item

I'm hoping someone can help me with this.

I have a single upload field, and I'm using the extraData() method to allow naming the file. I'm also using controls to start the upload.

The problem is this. When a user selects a file, and then changes the file before starting the upload, the newly selected file gets added to the queue. How can I override the queue with the last file selected so that I only upload 1 file at a time?

I thought setting multiple: false, would take care of it, but it doesn't appear to do anything, besides limit selection to a single file.

After changing the file, the queue looks like this:

0: a {data: File(103526), widget: l, jqXHR: null, status: 0, id: "zci1bjtmsk"}
1: a {data: File(103526), widget: l, jqXHR: null, status: 0, id: "05ox1qhs1xox"}

I am trying to do this:

onNewFile: function (id, file) {
    var queue = $(this).data('dmUploader').queue;
    var newFile = queue.length; // 1;
    queue = queue[newFile];
},

This gives me an undefined error, so I'm obviously accessing the object incorrectly.

Uncaught ReferenceError: Modernizr is not defined

This assumes that Modernizr is defined (Modernizr.touch) and if not, this will throw exception...
Is Modernizr needed?

Also demo-preview.js under demos is so generic that it could be located in src-folder...

Others than that, looks very nice, thanks!

maxFiles not working

hi,
these days I did some testing with this great plugin , and among the options I put maxfiles = 1 .
When I do the test , the plugin is not stopping me you if I try to load several files at once or if I try to upload multiple files at a time .

any help ?

br

Max

Single image upload?

Hi, this looks like a very useful plugin. Is it possible to limit uploads to a single image file at a time? I didn't see this among the documented options. Thanks!

Documentation error - extFilter setting

It appears that there's a small mistake in your documentation relating to the format of file extension lists. Your documentation states:

"Extension(s) comma separted for pre-submit validation."

but your script actually requires a list separated by semi-colons not commas.

Demos break under https

The latest versions of chrome and firefox block scripts that are served over http on a https site (see here)
Changing the demos to use the https version of code.jquery.com would solve this.

Image exif Orientation, When uploading by android device

Hi danielm,
Your work is super, any I really like this plugin, but I recently experienced an issue on android device.
when image uploaded it get rotate at 90 degree angle or different possibility. Is the any method to get rid of this situation.

thanks

How to update parent div after 'onComplete'?

I have dataTable with ajax content in the parent page. And I upload file with uploader. Then I need to update the table once the upload is complete. So I call with :

    onComplete: function(){
      $(body).find('#pflTable').ajax.reload();//update ajax table
    },

But the script error because 'body is not defined'. Please be advised!

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.