The AwsmUploader

A stand-alone and extremely feature-rich JavaScript class that lets you upload unlimited files of arbitrary size. Check out the overview to see what it can do for you.

This user interface uses the jQuery plug-in AwsmProgressBar, you can get it on codecanyon.net as well. The AwsmUploader uses a standard HTML5-progressbar by default.

My progress bar goes here!

Action:Start uploading by dropping files onto this progressbar! Don't worry, you can delete your files afterwards.

Feel free to upload multiple files by just selecting and (continuous) enqueuing them.
Some live-options hide this

Note: Some of these options will be finalized, when you start to drag files. Finalizing means, that the start()-method of the AwsmUploader gets called and basic options are set. This demo does not use approx. 20 of all available events and half of the available methods and options.




The maximum allowed number of parallel uploads
Set the size of a chunk (files are uploaded chunk-wise)

This demo allows you to upload any files up to 100 MiB. The statistics-box gives you also some information about the quota usage. Click delete to clear all files that have been uploaded by you or other users in order to fully use this demo.

The following buttons pause or continue the AwsmUploader, if there are any files to process (upload & read) on its queues. Note that pausing works file-wise. When the AwsmUploader actually pauses, an appropriate event (onUploadPause) is being fired. When you choose to abort all uploads, the AwsmUploader will destroy already uploaded chunks to preserve space. This action also rewinds the quota.

Some statistics hide this
Bytes transfered: 0 Bytes
Bytes total: 0 Bytes
Balance time: --:--:--
∑ speed active files: 0 B/s
∅ speed/file: 0 B/s
Quota usage:
Processing files: 0
Aborted & failed files: 0
Finished files: 0
is reading: false
is uploading: false
shall pause/is paused: false / false
TypeImageNameSize/Progress

The AwsmUploader is the advancement to the renown FileDropper 2. It lets you easily upload files by drag-n-drop with blank JavaScript (no Flash and no 3rd party plug-ins like jQuery required), HTML5 and PHP on the serverside.

What's so special about it then?

There are many answers to that question. The most awesome are:

Browser compatibility (as of July 2013)

Desktop browsersMobile browsers
Tested:Test yourself:
  • Firefox 13+
  • Chrome 20+
  • Internet Explorer 10+
  • Safari 6+ (untested)
  • Opera 12.10+
  • iOS 6 Safari 6+ (iPad 2+, iPhone 3GS, 4+)
  • Blackberry Browser
  • Opera Mobile 14+
  • Firefox for Android 22+

That's it?

Of course not. The AwsmUploader includes a lot more.

This component can only be bought on codecanyon.net. You can review and comment that component as well as make future suggestions there.

What's in the package and what do I need?

The package includes the stand-alone and fully independent JavaScript class AwsmUploader and its aforementioned nested classes and enumerations. Within the package you will find the PHP-classes (requires PHP 5) AUFile and AUFileChunk and a controller to handle those chunk-wise uploads. The package also includes a fully-implemented interface (similar to this one; with the AwsmProgressBar being replaced by a generic progressbar). The bundled implementation will work out of the box! You are not required to configure anything on the serverside (but there are some options you can adjust, of course).

As you see, the package being offered is rich and does not require you to implement and design your own interface (Note that this interface uses jQuery). You need little to no knowledge in JavaScript to make it work and only PHP 5 on your server to make it run. Modern browsers are supported, including Firefox 8+, and Chrome 16+. The Internet Explorer will fully support all native features in version 10.

It is quite easy to set up the AwsmUploader. Below you will find the default setup.





AwsmUploader



  
This is your droppable area where you drag files onto. Of course you can implement your own interface freely.

This table gives an overview about all public methods of the AwsmUploader. The documentation was taken from the original JavaScriptDoc. Scroll down to see the method overviews for the classes AwsmUploader.BinaryDataCollector, AwsmUploader.FeatureDetection, AUFile and AUFileChunk. The enumerations AwsmUploader.UserEvents and AwsmUploader.QueueTypes are placed at the end.

Methods of the class AwsmUploader

This is the main class of the package. Instances are used to handle droppable areas and files dragged onto them. At the same time this is a namespace containing two public static nested classes and the two aforementioned enumerations as public static frozen objects.
Since 3.0.3: The new method enqueueFileForUpload(File file) was added so that you now can feed the AwsmUploader with files from arbitrary sources (e.g. [multiple] file inputs, like above).

Constructornew AwsmUploader( (HTMLElement) dropTarget )

The constructor is used to create new instances of the AwsmUploader. The new-keyword is optional. Store the instance in a variable to further use it and call methods.

  • (HTMLElement) dropTarget is the element you want to use as droppable area. Must not be null.
  • Exception, if the argument dropTarget is not an HTMLElement.
(AwsmUploader) this instance of the AwsmUploader
addNotAllowedRegex.addNotAllowedRegex( (RegExp) regex )

Supply your own regexes if you want the AwsmUploader to exclude even more files by their names.

  • RegExp regex the expression to match files against.
(AwsmUploader) this instance of the AwsmUploader
addUploadParam.addUploadParam( (String) paramName, (String) paramValue )

Use this function to add parameters to the upload POST request.

  • String paramName the name of the parameter.
  • String paramValue the value.
(AwsmUploader) this instance of the AwsmUploader
calcBytes.calcBytes( (Integer) bytes [, (Integer) precision ] )

Formats an amount of bytes to the best fitting unit with a fixed decimal precision of 2. Returns a string like '2.54 MiB' and uses the IEC prefixes to the base of 2 (MiB instead of MB for example).

  • (Integer) bytes the number of bytes (filesize)
  • (Integer) precision the precision, defaults to 2
(String) the formatted version with correct prefix
cancel.cancel( void )

Aborts all files in the reading and pending queue and shifts them to the aborted queue.

(AwsmUploader) this instance of the AwsmUploader
continue.continue( void )

Signalizes the AwsmUploader that it can continue uploading files to the server. Unpauses the AwsmUploader, if it was in an idle state.

(AwsmUploader) this instance of the AwsmUploader
destroy.destroy( void )

Use this to unbind the AwsmUploader from your drop-target. You can delete the instance-variable afterwards. This is the only void-method as there is nothing to return, the AwsmUploader becomes unusable.

undefined
enqueueFileForUpload.enqueueFileForUpload( (File) file )

New: Generic function to enqueue files for upload coming from an arbitrary source (e.g. file inputs or other droppable areas). This function silently skips the file if it is disallowed. To check the success, register a custom handler for the event 'onFileEnqueue' to listen for that.

  • (File) file the file to enqueue. Its name is checked by the supplied regexes for disallowed files.
(AwsmUploader) this instance of the AwsmUploader
getAUFileById.getAUFileById( (String) auId )

Getter for one AwsmUploaderFile by its ID. Looks up the ID in all queues (dropped, pending, completed, aborted and failed).

  • (String) auId the ID of the AwsmUploaderFile you want
  • Exception, if the file is not contained within any of these queues.
(AwsmUploaderFile) the desired file
getAverageSpeed.getAverageSpeed( (Boolean) includeFailedFiles )

Returns the average speed in bytes per second of all successfully uploaded files and also all failed and aborted files if you set includeFailedFiles to true. Returns the current speed if all of these queues have been empty.

  • (Boolean) includeFailedFailes set it to true to also include the speed of aborted / erroneous files.
(Number) bytes per second
getBinaryDataCollector.getBinaryDataCollector( (String) collectorId )

Getter for a certain BinaryDataCollector.

  • (String) collectorId the ID of the collector you want to get.
  • Exception, if no such collector is registered
(BinaryDataCollector) the collector with the specified ID
getCurrentQuota.getCurrentQuota( (Boolean) includePendingFiles )

Getter for the quota used so far. Only regards completely uploaded files. Includes the static quota.

  • (Boolean) includePendingFiles set this to true to include the quota usage of pending files.
(Integer) the quota of all uploaded files
getCurrentQuotaUsage.getCurrentQuotaUsage( (Boolean) includePendingFiles )

Returns a percentage of used quota and allowed quota, something between 0 and 1 (inclusive). Static quota is already included through getCurrentQuota().

  • (Boolean) includePendingFiles set this to true to include the quota usage of pending files.
(Double) the quota-ratio
getCurrentSpeed.getCurrentSpeed( (Boolean) getTotalSpeed )

Returns the average speed in bytes/second of all files that are currently being uploaded.

  • (Boolean) getTotalSpeed set it to true if you want the sum of all speeds and not the average speed of all loading files.
(Number) bytes per second
getEta.getEta( void )

Returns the maximum estimated time amount of all uploading files. This means, the file that is about to take the most time for uploading is considered to represent the greatest amount of time needed, because the AwsmUploader works with parallel uploads.

(Double) the maximum ETA of all files in seconds
getFailedQuota.getFailedQuota( void )

Returns the amount of bytes of the files, that haven't been uploaded successfully. AUFiles from the two queues Failed and Aborted are considered.

(Integer) the amount of bytes
getMaxUploadSize.getMaxUploadSize( void )

Getter for the maximum allowed upload size in bytes per file. Returns the default value of -1 if not set.

(Integer) the number of bytes per file allowed max
getNumFiles.getNumFiles( (AwsmUploader.QueueTypes) queueType )

Returns the number of files on the specified queue.

  • (AwsmUploader.QueueTypes) queueType the type of queue
  • Exception, if the type of queue is not supported
(Integer) the number of files on that particular queue
getOverallProgress.getOverallProgress( void )

Returns the average progress of the total bytes and the processed bytes. Processed refers here to the read and uploaded bytes.

(Number) the overall progress, 0 <= progress <= 1
getQueueReadAndTotal.getQueueReadAndTotal( (AwsmUploader.QueueTypes) queueType )

The same as getQueueUploadedAndTotal, but for the amount of read bytes here. The amount of read bytes in the aborted and failed queues includes the sizes of the aborted / failed chunks of course.

  • (AwsmUploader.QueueTypes) queueType the type of queue
  • Exception, if the type of queue is not supported
(Object) with keys 'loaded' and 'total'
getQueueUploadedAndTotal.getQueueUploadedAndTotal( (AwsmUploader.QueueTypes) queueType )

Returns an object containing the number of bytes that have been uploaded so far and that contains the total size of that queue.

  • (AwsmUploader.QueueTypes) queueType the type of queue
  • Exception, if the type of queue is not supported
(Object) with keys 'loaded' and 'total'
getQuota.getQuota( void )

Getter for the static used quota.

(Integer) the quota you set before with setQuota()
getQuotaMax.getQuotaMax( void )

Getter for the maximum allowed quota.

(Integer) the maximum quota in bytes
getQuotaUsage.getQuotaUsage( void )

Returns the current quota usage in percent. Only takes care of the static quota set by setQuota().

(Double) the ratio (0 <= ratio <= 1)
getReadAndTotal.getReadAndTotal( void )

Returns an object with the number of bytes read so far and the total amount of bytes on the three queues dropped, pending and completed.

(Object) with keys 'loaded' and 'total'
getUploadParams.getUploadParams( void )

Getter for the upload parameters. Returns a copy of the array of parameters, so that you cannot change them. To set/add/remove a parameter, use the appropriate function.

(Array) the upload parameters as array of arrays with k/v pairs
getUploadProgress.getUploadProgress( void )

Returns the percentage of the overall upload progress. Uses the method getUploadedAndTotal() to calculate the bytes.

(Number) a ratio between 0 and 1 (inclusive)
getUploadedAndTotal.getUploadedAndTotal( void )

Returns an object with the number of total uploaded bytes and the total size of the three queues dropped, pending and completed. Useful to calculate an overall progress for example.

(Object) with keys 'loaded' and 'total'
hasBinaryDataCollector.hasBinaryDataCollector( (String) collectorId )

Will look up, whether a certain BinaryDataCollector is registered.

  • (String) collectorId the ID of the collector you want to check
(Boolean) true if so, false otherwise
isOnQueue.isOnQueue( (AUFile) auFile, (AwsmUploader.QueueTypes) queueType )

Returns true, if a given AUFile is on the specified queue at the moment.

  • (AUFile) auFile the AUFile you want to ask for
  • (AwsmUploader.QueueTypes) queueType the queue you want to check for
(Boolean) true if file is on asked queue
isReading.isReading( void )

Returns the reading state of the AwsmUploader.

(Boolean) true, if it is reading at the moment.
isUploadPaused.isUploadPaused( void )

Returns the state of the AwsmUploader. Note: If you want to check if the AwsmUploader really is paused, you will need to wait for the event AwsmUploader.UserEvents.onUploadPause to occur.

(Boolean) true, if the AwsmUploader is paused or is in a state where it waits for an upload to finish and then to pause.
isUploading.isUploading( void )

Returns the uploading state.

(Boolean) true if uploading is in progress.
isUploadingComplete.isUploadingComplete( void )

Returns if uploading all files is complete.

(Boolean) true if all files have been uploaded.
pause.pause( void )

Signalizes the AwsmUploader that it should pause before processing the next file. Note that the AwsmUploader pauses file-wise.

(AwsmUploader) this instance of the AwsmUploader
registerBinaryDataCollector.registerBinaryDataCollector( (AwsmUploader.BinaryDataCollector) dataCollector )

Registers a new BinaryDataCollector for an AUFile. Consider that only one collector can be registered per file. It is a good practice to create a collector when the event onFileBeforeReadStart (or any other event that fires before the file is being read) is being triggered.

  • (AwsmUploader.BinaryDataCollector) dataCollector the collector you want to register.
(AwsmUploader) this instance of the AwsmUploader
registerHandler.registerHandler( (AwsmUploader.UserEvents) handlerType, (Function) callback )

Used to register (set) all custom user handlers that receive a custom AwsmUploader user event when triggered. Use AwsmUploader.UserEvents to supply one possible handler type. If you re-register a callback, the previously registered one is being overridden.

  • (AwsmUploader.UserEvents) handlerType one of AwsmUploader.UserEvents
  • (Function) callback that may accepts appropriate arguments. See the enumeration of user events for detailed method signatures.
  • Exception, if the handler type is not supported.
(AwsmUploader) this instance of the AwsmUploader
removeBinaryDataCollector.removeBinaryDataCollector( (String) collectorId, (Boolean) shouldFreeFirst )

Removes a BinaryDataCollector from the set of registered collectors. Calls the collector's free()-method before removing it, if you want to do so (recommended).

  • (String) collectorId the ID of the collector you want to remove.
  • (Boolean) shouldFreeFirst set this to true to tell this function to call the collector's free()-method before removing it.
(AwsmUploader) this instance of the AwsmUploader
removeUploadParam.removeUploadParam( (String) paramName )

Use this function to remove upload parameters immediately. Does not affect running POST requests but the very next one.

  • (String) paramName the name of the POST parameter to remove
(AwsmUploader) this instance of the AwsmUploader
setChunkSize.setChunkSize( (Integer) size )

Set the size per chunk in bytes. Default value for chunks is 512 KiB (524288 Bytes).

  • (Integer) size the the size in bytes per chunk
(AwsmUploader) this instance of the AwsmUploader
setHttp401Credentials.setHttp401Credentials( (String) user, (String) pass )

Used to set the HTTP-401 credentials to authorize the requests. If either of the parameters is not a string or an empty string, the credentials will be resetted, what results in requests that cannot take HTTP-401 authorization.If both user and pass are non-empty strings this method will enable authorization, disable it otherwise.

  • (String) user the username or null
  • (String) pass the password or null
(AwsmUploader) this instance of the AwsmUploader
setMaxUploadSize.setMaxUploadSize( (Integer) size )

Setter for the maximum upload size in bytes (per file).

  • (Integer) size the max size in bytes you allow per file
(AwsmUploader) this instance of the AwsmUploader
setNumParallelUploads.setNumParallelUploads( (Integer) numUploads )

Sets the number of maximum allowed parallel uploads. The AwsmUploader processes and transmits one chunk after the other per file, but it can process multiple files at a time. Use this setter to suit your needs and match your bandwidth.

  • (Integer) numUploads the number of uploads you allow in parallel. Set it to sth. < 0 to enable the default of 2.
(AwsmUploader) this instance of the AwsmUploader
setQuota.setQuota( (Integer) currentQuota )

Function to set the previously used quota. Will be added to the current used quota if asked for that.

  • (Integer) currentQuota the amount in bytes
(AwsmUploader) this instance of the AwsmUploader
setQuotaMax.setQuotaMax( (Integer) quota )

Setter for the maximum usable quota. The AwsmUploader will abort future transmissions if an upload would lead to the exceedance of this maximum.

  • (Integer) quota the maximum allowed size in bytes
(AwsmUploader) this instance of the AwsmUploader
setUploadParam.setUploadParam( (String) paramName, (String) paramValue )

Shorthand function that wraps addUploadParam() and removeUploadParam().

  • (String) paramName the name of the parameter
  • (String) paramValue the value
(AwsmUploader) this instance of the AwsmUploader
setUploadPath.setUploadPath( (String) path )

Set the path to post the file's chunks to. Tests the supplied path also for a different domain, what would cause the AwsmUploader to try to use CORS-requests. This path receives the following parameters via POST:
- the chunk itself as binary, namely 'upload'
- the filename as 'filename'
- the chunk's index, starting with 0 to numbers of chunks - 1 as 'chunk'
- the total amount of chunks, namely 'totalchunks'

  • (String) path the upload path to post to, defaults to 'upload.php'
(AwsmUploader) this instance of the AwsmUploader
setWithCredentials.setWithCredentials( (Boolean) withCredentials )

Setter for the withCredentials-propery of newly created CORS-requests.

  • (Boolean) withCredentials true, if property should be set
(AwsmUploader) this instance of the AwsmUploader
start.start( void )

Can only be called once. You should call it after you hooked everything up. That means, sizes, quotas, callbacks and so on. This function binds the drop-handler to your 'dropTarget'. Note: Do not forget to call this method, otherwise you cannot upload files! Due to the fact, that this method returns the current instance, you could use it in a chain: var myUploader = new AwsmUploader(myDiv).setUploadPath('/myDir/upload.php').setQuotaMax(50 * 10e7).start();

(AwsmUploader) this instance of the AwsmUploader

Methods of the class AwsmUploader.BinaryDataCollector

Public static class for collecting binary data of AUFileChunks when they finished reading. Intended use is for building data-Url's. DataUrl's are useful for displaying images or to play back sounds and music once the file has been finished reading. This class should be used carefully as DataUrls may cause very high memory usages. For example reading many pictures into DataUrls and displaying them will cause most browsers to become unresponsive and to use great amounts of memory, if those pictures have higher resolutions. Anyways, for many purposes this class can perform well (when uploading many thumbnail-sized images or short sounds e.g.).

Constructornew AwsmUploader.BinaryDataCollector( (AUFile) auFile )

The constructor is used to create new instances of the BinaryDataCollector. The new-keyword is optional. Store the instance in a variable to further use it and call methods.

  • (AUFile) auFile the AUFile to register this collector for. Only one collector can be registered per AUFile.
  • Exception, if the parameter auFile is not a AUFile.
(AwsmUploader.BinaryDataCollector) this instance of the BinaryDataCollector
addChunkData.addChunkData( (Integer) aufChunkId, (BinaryString) data )

Adds data to the collector. When a chunk finished reading, the AwsmUploader will call this method to add the read data.

  • (Integer) aufChunkId the ID of the chunk (its index)
  • (BinaryString) the data as a binary string, not BLOB
(AwsmUploader.BinaryDataCollector) this instance of the BinaryDataCollector
free.free( void )

This member will free all data stored in the array of chunks. It finally cuts down its size to zero.

(AwsmUploader.BinaryDataCollector) this instance of the BinaryDataCollector
getId.getId( void )

Getter for the collector's ID. It is the same ID as the AUFile's it was created for. The IDs need to correspond in order to maintain the AwsmUploader's inner management (otherwise the collector can not be retrieved from the set of collectors).

(String) the ID of this collector
hasAllData.hasAllData( void )

Checks, if all data is available.

(Boolean) true if so, false otherwise
toDataUrl.toDataUrl( (Function) callback )

This method builds a DataUrl out of the collected data by concatenating the collected ArrayBuffers.

  • (Function) callback a function that shall accept one argument of type string being the DataURL (toDataUrl works asynchronously)
  • Exception, if not all data is available yet
(AwsmUploader.BinaryDataCollector) this instance of the BinaryDataCollector

Methods of the class AwsmUploader.FeatureDetection

Public static class for detecting all features the AwsmUploader needs. Inspect the features-object to see, whats needed.

Constructornew AwsmUploader.FeatureDetection( void )

Public static class for detecting all features the AwsmUploader needs. Inspect the features-object to see, whats needed. The new-keyword is optional. Store the instance in a variable to further use it and call methods.

(AwsmUploader.FeatureDetection) this instance of the AwsmUploader.FeatureDetection
allFeaturesAvailable.allFeaturesAvailable( void )

Returns false, if one of the features is not available.

(Boolean) true, if all features are available.
getFeatures.getFeatures( void )

Getter for the private features-object.

(Object) the features as K/V-map (String/Boolean)

Methods and properties of the class AUFile

Private nested class that depicts a AwsmUploader's file. This kind of file has dedicated properties and also a private nested class that represents chunks, the AUFileChunk. The new-keyword is optional. The AUFile is exposed in numerous events. You can access its properties and methods then freely. You can also gain access to all the AUFileChunks of an AUFile this way.

The following list represents all publicly accessible properties.

  • ID: To provide a public unique identifier for this file. Will be in the format of an UUID and begins with 'auf'.
  • Name: The formatted file name, under this file also gets uploaded. A formatted filename only contains alphanumeric characters, hyphens and underscores. Ugly double hyphens and underscores are stripped out.
  • File: The bare file-object from the drop-event.
  • Size: The file's size in bytes.
  • Mime: The file's mime-type as string.
  • Dropped: The date/time the file was dropped as 13-digit Unix-timestamp.
  • IsImage: True if the name matches the regex or the mime matches the mime-regex.
  • IsUploadAborted: State management, we set it to true if abort or error.
abortRead.abortRead( void )

Public function to abort the reading process of this file. Also, calls the abort()-method of all chunk's Readers and releases them immediately afterwards. Sets this file's IsUploadAborted-state to true, so no more chunks are being transmitted. The AUFileChunks's state is also set to true.

(AUFile) this instance of the AUFile.
abortUpload.abortUpload( void )

Cancels the upload process of this AUFile. Sets also the IsUploadAborted-state to true and calls the abort()-method of all chunk's XMLHttpRequests. Sets the AUFileChunk's IsUploadAborted-state to true.

(AUFile) this instance of the AUFile.
getChunk.getChunk( (Integer) index )

Used to retrieve one AUFileChunk by its ID (index).

  • (Integer) index the ID (index) of the chunk you want.
  • Exception, if the chunk could not be found.
(AUFileChunk) the chunk with ID index
getChunkReadCompleteRate.getChunkReadCompleteRate( void )

Returns a ratio between 0 and 1 (inclusive) for all bytes read so far. Useful for displaying percentages.

(Number) the ratio 0 <= ratio <= 1.
getChunkUploadCompleteRate.getChunkUploadCompleteRate( (Boolean) includeFailed )

Again, pretty much the same as getChunkReadCompleteRate(), but here for uploaded bytes. This method also can include bytes of failed or aborted chunks.

  • (Boolean) includeFailed set it to true to include bytes of failed/aborted chunks.
(Number) the ratio of uploaded bytes, 0 <= ratio <= 1.
getCurrentUploadSpeed.getCurrentUploadSpeed( void )

Due to a core change of the AwsmUploader, only one chunk can upload at a time. So this method iterates this AUFile's chunks and returns the current speed in bytes/second of the uploading one.

(Double) the speed in bytes/second.
getEta.getEta( void )

Uses the method getCurrentUploadSpeed() and gives back the amount of estimated seconds, the rest of the file will need to complete the upload.

(Double) the estimated seconds to complete the upload.
getNumChunks.getNumChunks( void )

Returns the number of chunks, this file has.

(Integer) the number of chunks of this AUFile
getNumReadBytes.getNumReadBytes( (Boolean) includeFailed )

Returns the amount of read bytes for this file.

  • (Boolean) includeFailed set it to true to also include the read bytes by aborted chunks.
(Integer) the amount of bytes read by all chunks so far.
getNumUploadedBytes.getNumUploadedBytes( (Boolean) includeFailed )

Nearly the same as getNumReadBytes(), but this time it's for the amount of uploaded bytes.

  • (Boolean) includeFailed set it to true to also include the read bytes by aborted chunks.
(Integer) the amount of bytes uploaded by all chunks so far.
getOverallCompleteRate.getOverallCompleteRate( void )

Returns the average ratio of getChunkReadCompleteRate() and getChunkUploadCompleteRate(false) without failed files.

(Number) the overall ratio, 0 <= ratio <= 1.
getUploadSpeed.getUploadSpeed( void )

Calculates the upload speed of this file in bytes per second. If this file is currently uploading, it returns the result of the method getCurrentUploadSpeed(). Otherwise it takes the start of the first chunk and the end time of the last chunk that finished uploading for calculating the total needed time.

(Double) the upload speed in bytes/second.
isReading.isReading( void )

Iterates all chunks and returns true, if at least one of them is reading at the moment.

(Boolean) true if this file is reading.
isUploading.isUploading( void )

Same as isReading(), but for the uploading chunks. Asks the chunks for their IsUploading property.

(Boolean) true if at least one chunk is actively uploading.

Methods and properties of the class AUFileChunk

Private nested class that corresponds to one Chunk. It knows its size, start- and end-index and has its own XMLHttpRequest and FileReader. Objects of this type are exposed by uEvts through the accessible property 'auFile' and then by accessing the methods of that AUFile. Usually you do not need to access chunks.

The following list represents all publicly accessible properties.

  • ID: This chunk's ID (its index, zero-based).
  • Loaded: The amount of bytes read.
  • Uploaded: The amount of bytes uploaded.
  • Total: The amount of bytes this chunk has.
  • IsReading: True if this chunk currently reads data.
  • IsUploading: True if this chunk currently uploads data.
  • IsUploadAborted: Will be set to true if an error occurred or the wrapping file should be aborted. No new chunks will be read or uploaded when this was set to true.
  • OffsetStart: The index to start slicing the file.
  • OffsetEnd: The index to end slicing this file.
  • ReadComplete: Will be set to true if the chunk finished reading its data.
  • UploadComplete: Will be set to true if the chunk finished uploading its data.
  • StartUploadTime: When uploading starts this will be a 13-digit Unix-timestamp.
  • EndUploadTime: When uploading ends this will be a 13-digit Unix-timestamp.
  • Reader: This chunk's own FileReader.
  • XHR: This chunk's own XMLHttpRequest.
free.free( void )

The only method a chunk has. Frees the reader and its used memory. Should be called immediately after you do not need the read data anymore. The wrapping AUFile does this automatically.

(AUFileChunk) this instance of the AUFileChunk.

Properties of the enumeration AwsmUploader.UserEvents

A public (frozen) enum of all available events, that can be registered on the AwsmUploader. Use them to register your custom event handlers with the public method registerHandler, that takes one of the constants below as first argument (and your handler as second). Take a look at the beginning of the AwsmUploader class to see, what type of event is passed to your callback (if any). Basically there are only two types: Either it is an 'uEvt' (see the private function createUserEvent() for what it contains or it is an AUFile that is passed. The uEvt also holds a reference to the AUFile. Some callbacks do not receive an argument, 'uploadAllFilesComplete' for example.
The event type onGeneralActionHandler is an exception to this. It is always been triggered if something happens. This means, this handler is always triggered if one of the user events below occurrs. Accepts one argument, the handlerType (AwsmUploader.UserEvents), to give you an idea what kind of event actually happened.
The event type errorHandler is another exception to this. It accepts one function and passes the error message as string as only argument to it. This event uses window.alert(msg) by default.

The following list of event types contains those events that trigger a callback with no arguments.

  • readAllFilesCompleteHandler: When all files have been read, no argument
  • uploadAllFilesCompleteHandler: No argument, called when all files have been processed
  • onUploadPauseHandler: Called when the pause actually occurs. Calling pause() only sets the AwsmUploader's state to pause. This means it does not continue to read new chunks of files currently being processed (and therefore no new chunks are being transmitted). So this callback is triggered when the AwsmUploader wants to continue with the next chunk but you wanted it to pause it before by calling pause().

The following list of event types contains those events that trigger a callback that receives one argument of type AUFile.

  • onFileDropHandler: Called when the file is being dropped
  • onFileTooLargeHandler: Called when the file is too large and if you have set the maximum upload size before.
  • onQuotaExceedsHandler: Same, but when quota is about to exceed.

The following list of event types contains those events that trigger a callback that receives one argument of type uEvt. A uEvt is an object of key/value pairs and contains the keys
- id (the AUFile's ID),
- name (the AUFile's name),
- mime (the AUFile's mime-type),
- size (the AUFile's size),
- auFile (the AUFile itself),
- aufChunk (the current AUFileChunk the event concerns),
- chunkSize (the chunksize you set via setChunkSize()),
- totalChunks (the amount of chunks this AUFile has (calls getNumChunks()),
- isImage (equal to AUFile.IsImage),
- lengthComputable (true if the length of that event is computable),
- loaded (the amount of bytes that were read/uploaded if lengthComputable, -1 otherwise),
- total (the total amount of bytes if lengthComputable, -1 otherwise)

  • onChunkBeforeReadStartHandler: Called for every single chunk before the reading starts.
  • onChunkReadStartHandler: When the read starts.
  • onChunkReadProgressHandler: Called upon every step the progress takes.
  • onChunkReadEndHandler: When reading came to an end.
  • onChunkReadErrorHandler: If an error occurred.
  • onChunkReadAbortHandler: If reading has been aborted.
  • onFileBeforeReadStartHandler: Called for the first chunk before it starts reading.
  • onFileReadStartHandler: When the first chunk of the file starts reading.
  • onFileReadCompleteHandler: When the last chunk finished reading.
  • onChunkBeforeUploadStartHandler: Before each chunk starts uploading.
  • onChunkUploadStartHandler: When the chunk starts uploading.
  • onChunkUploadProgressHandler: For each progress step in the uploading process of each chunk.
  • onChunkUploadEndHandler: When a chunk successfully finished uploading.
  • onChunkUploadErrorHandler: When an error occurred.
  • onChunkUploadAbortHandler: When uploading has been aborted.
  • onFileUploadStartHandler: Shorthand function if first chunk start to transmit.
  • onFileUploadCompleteHandler: Shorthand, if last chunk finishes.
  • onFileAbortHandler: Shorthand, if one chunk was aborted.

Properties of the enumeration AwsmUploader.QueueTypes

Public (frozen) enum for the queue types the AwsmUploader has. Use them to specify the appropriate event to get the correct details for the queue you want.
The AwsmUploader has five queues. The 'Dropped' queue holds all files that were dropped but haven't even been read yet. The 'Pending' queue temporarily holds the files, that are being processed. This means these files are reading and/or uploading right now. The 'Completed' queue holds all successfully completed (read and uploaded) files. The 'Aborted' queue receives files that have received a user-triggerd abort event. The 'Failed' queue by contrast receives the files, that caused an error whilst reading or uploading.

  • Dropped: This queue contains all files that have been dropped onto the droppable area and wait to be processed.
  • Pending: This queue contains all files that currently read and/or upload.
  • Completed: All completely processed files can be found on this queue.
  • Aborted: Contains files that were aborted.
  • Failed: Contains erroneous files.

The AwsmUploader comes bundled with the serverside PHP you need to upload awesome files. It consists of a controller and the two JavaScript-counterpart-classes AUFile and AUFileChunk. You need PHP5 to make it work.

The upload controller

The controller starts a session to maintain an overview over all uploaded chunks and files. The communication between the controller and the clientside JavaScript is done only via JSON. The returned JSON has the four keys 'error' (Boolean), 'msg' (String), 'filename' (String) and 'thumbnail' (String or NULL). 'Error' will indicate if an error occurred. If so, the key 'msg' will contain details. The key 'filename' will hold the actual filename of the file you uploaded. It can be different if you have chosen not to overwrite existing files. The key 'thumbnail' will hold the relative path and filename of the corresponding generated thumbnail.

The controller has its own error-handler for fatal (non-recoverable) errors. It also checks for disallowed files by using regular expressions. It also handles CORS-requests. The action 'abort-file' allows to abort the upload of a file. Aborting a file deletes all its chunks and removes it from the session. This action needs the file's name. The action 'get-quota' recursively checks the already used quota in the upload directory. The resulting JSON will contain the key 'quota' holding the corresponding amount of bytes used.

Methods and constants of the class AUFile.class.php

Represents one file that gets uploaded. One file consists of a certain amount of chunks. If all chunks are available, you can write the file. This class also can create thumbnails of uploaded images. Adjust the constants to fit your thumb-needs.
Since v1.1: Prefixed constants with 'DEFAULT_', as they now are default arguments to the instance-functions; you can specify own values from now on.
Since 1.2: Chunks are not stored in array anymore and are written immediately if they arrive. We now can be sure that they arrive in the correct order and also do not need to sort them. Note that some constants and function were added and removed; the API slightly changed.

The following list shows all public constants of this class.

  • AUFile::IMG_MATCH: Regular expression to match images by filename.
  • AUFile::DEFAULT_THUMB_WIDTH: The maximum thumbnail width in pixels
  • AUFile::DEFAULT_THUMB_HEIGHT: The maximum thumbnail height in pixels
  • AUFile::DEFAULT_THUMB_QUALITY: Quality of the thumbnails for the use with imagejpeg().
  • AUFile::DEFAULT_THUMB_QUALITY_PNG: Quality of the thumbnails for the use with imagepng().
  • AUFile::DEFAULT_THUMB_MAX_MPIXELS: Set the maximum megapixels for images to create thumbnails from. It is useful to limit this as PHP can has severe memory limits. If the memory limit exceeds, the controller will handle that appropriate.
  • AUFile::CHUNK_WRITE_RETRIES: If another instance writes into the file, we wait X times for the specified time to acquire the lock on the resulting file.
  • AUFile::CHUNK_WRITE_RETRY_TIMEOUT: The time we wait inbetween the approaches of acquiring the lock.
Constructor(public) __construct( string $id, string $name, int $numChunks )

C'tor, takes the file's id, name and number of chunks. The new-keyword is required.

  • string $id the name's hash (with sha1())
  • string $name the file's name
  • int $numChunks the amount of chunks the resulting file will have.
(AUFile) this instance of the AUFile.
getId(public) ->getId( void )

Getter for the file's id.

(string) the id.
getName(public) ->getName( void )

Getter for the file's id.

(string) the id.
addChunk(public) ->addChunk( AUFileChunk $chunk )

Adds a chunk to this file. Does not sort the chunks. This is done later immediately before the file gets written.
Removed in 1.2.

  • AUFileChunk $chunk an instance of a compatible AUFileChunk
(void)
allChunksAvailable(public) ->allChunksAvailable( string $dir )

Checks, if all chunks have been successfully uploaded.
Removed in 1.2.

  • string $dir the directory to check for chunks in
(boolean) true, if all chunks are available
unlinkChunks(public) ->unlinkChunks( string $dir )

Should be called if something goes wrong. Deletes all (partially) finished chunks of this file to reallocate the space.
Since 1.2 this method tries to also remove this file.

  • string $dir the directory where the chunks have been stored in
(void)
writeFile(public) ->writeFile( string $dir, string $name )

Writes all chunks into the resulting file. This is done in a series, so after a chunk was written it gets deleted immediately. Updates the AUFile's name to the actual one.
Removed in 1.2.

  • string $dir the directory where the chunks reside (and where the resulting file will be stored in)
  • string $name the name of the file we write
  • Exception, if not all chunks are available or one of the chunks can not be read or there is an IO problem with the resulting file.
(void)
sortChunks(private static) ->sortChunks( AUFileChunk $ac, AUFileChunk $bc )

When all chunks are available, we do not have an idea in which order they arrived, so we need to sort them to write them in the right order.
Removed in 1.2.

  • AUFileChunk $ac the first chunk to compare
  • AUFileChunk $bc the second chunk
(int) -1, if $ac should be written before $bc; 1 otherwise
getQuotaUsage(public static) ->getQuotaUsage( string $baseDir )

This function recursively calculates the used quota in a directory.

  • string $baseDir the path to start in
(int) the amount of bytes already used
checkNameAndGetName(public static) ->checkNameAndGetName( string $path, string $file )

Checks, if the file name is already used in the given path and iterates the available names by appending a counter to the name until the name is free.

  • string $path the path to check the name in
  • string $file the file name to check initially
(string) the first available name
isImage(public) ->isImage( void )

Returns true, if PHP can make the guess, that this AUFile also is an image, based on its extension.

(boolean) true, if PHP thinks this is an image.
saveThumb(public) ->saveThumb( string $dir, string $name [, int $qualityPng = self::DEFAULT_THUMB_QUALITY_PNG [, int $qualityJpg = self::DEFAULT_THUMB_QUALITY ]] )

Should be called right after createThumb() to store the processed thumbnail to a file. Since version 1.1 this function uses defaults arguments for thumbnail quality levels.

  • string $dir the dir to store the image in
  • string $name the new file's name
  • int $qualityPng the default quality for png-thumbnails. Ranges until 9 (100%) and defaults to the built-in constant's value.
  • int $qualityJpg the default quality for jpg-thumbnails. Values correspond to actual percentage.
  • Exception, if thumb has not been created or can not be stored.
(void)
createThumb(public) ->createThumb( string $dir [, int $thumbWidth = self::DEFAULT_THUMB_WIDTH [, int $thumbHeight = self::DEFAULT_THUMB_HEIGHT [, long $maxMegaPixels = self::DEFAULT_THUMB_MAX_MPIXELS ]]] )

Will write the thumbnail if the uploaded file is completely available (all chunks are here) and if PHP can process the image (must be either png, gif or jpg). Since version 1.1 this function uses default arguments for the width and height of a thumbnail and lets you override the maximum allowed resolution of images to process.

  • string $dir the path this file is in
  • int $thumbWidth the resolution in pixels for the maximum width of a thumbnail.
  • int $thumbHeight the same as $thumbWidth, but for the height here instead.
  • long $maxMegaPixels you can use this to allow the creation of thumbnails for very large images. Note that very high values can consume a lot of memory.
  • Exception, if an error occurs during the thumb creation process.
(void)

Methods of the class AUFileChunk.class.php

This class represents a chunk that can be part of an AUFile.
Since 1.2: The method isWritten() was removed as it is not longer needed (chunks are written immediately now).

Constructor(public) __construct( int $id, int $size )

Constructor, takes the id and size.

  • int $id the chunk's id (same as its index, zero-based)
  • int $size the chunk's size in bytes
(AUFileChunk) this instance of the AUFileChunk.
getId(public) ->getId( void )

Getter for the chunk's id.

(int) the id
getSize(public) ->getSize( void )

Getter for the chunk's size.

(int) the size
getName(public) ->getName( AUFile &$AUFile )

Returns the chunk's fully qualified name. That is, its id concatenated with its file's id. The name is the file name.

  • &AUFile $auFile the AUFile to get the ID from
(string) the chunk's file name
isWritten(public) ->isWritten( string $dir, AUFile &$AUFile )

Function to check, if this chunk has been written so far and is available.
Removed in 1.2.

  • string $dir the path to check the existence in
  • &AUFile $auFile the AUFile to get the ID from
(boolean) true, if chunk is available