SlashUploader

Javascript multi-features plugin to upload files - dependency-free, with cross-domain support, legacy browsers compatibility, fully-customizable design, and many more options.

Download Github

Version 1.5.8

SlashUploader

Features

  • Cross-Domain

    SlashUploader support cross-domain upload on all browers, so you can locate your server files anywhere, no matter on which domain the plugin is hosted in.
  • Old Browsers Support

    SlashUploader supports old browsers all the way back to IE8.
    Full compatibility list can be seen here.
  • Dependency-free

    Code is written in native vanilla JS and doesn't use any external sources, so there's no limitation to use a specific framework.
  • Preview Images

    When uploading images, a preview of the images is seen within the plugin progress indication. Pretty cool. Check out the demos.
  • Drag & Drop

    Allow the user to select his files by dragging them to the browser window from his computer.
  • Get Files Metadata

    Get files metadata upon files selection, including data such as width & height, image rotation (based on camera orientation when picture was capruted), media file duration, file size, file type, ect.
  • Fully Customizable

    With plenty of options to use, with the ability to change the plugin CSS easily, or to simpley use the plugin over you own custom HTML element without changing its layout - you can have the plugin look whatever you want it to.
  • RTL

    Support Right-to-Left direction. Useful for RTL languages such as Hebrew or Arabic.
  • Validate Before Upload

    Fully-customizable validation, that allows you to validate user files before uploading them. So you can limit upload based on parameters such as file type, size, width, height, duration, ect.
  • Responsive

    Plugin layout is responsive, so you can use it in any of your elements, and size will adjust.
  • Show Upload Progress

    See upload progress for each selected file, and for all files together.
  • Trigger Events

    The following events and their data can be used: files selected, files uploaded, upload progress, file deleted, error occurred, and upload canceled.
  • Cancel Upload

    "Cancel" button allows user to abort his current upload.
  • Ability to Disable

    Plugin can be set as "disable", so user interaction won't be possible.

Demo

Embed SlashUploader JS and SlashUploader CSS tags in your HTML file, and create a simple DIV:
1
2
3
4
5
6
7
8
9
<html>
<head>
	<script src='./SlashUploader/SlashUploader.min.js'></script> 
	<link href='./SlashUploader/SlashUploader.min.css' type='text/css' rel='stylesheet'>
</head>
<body>
	<div id='my-uploader' style='width: 600px; height: 80px;'></div>
</body>
</html>

Declare a SlashUploader instance:
1
var myUploader = new SlashUploader (document.getElementById("my-uploader"));

And Voila!
Result:
More demos can be found here.



Demos



Below are some examples for SlashUploader usage.




Default



Initilize SlashUploader without modifing anything.

Code:
1
var myUploader = new SlashUploader (document.getElementById("my-uploader"));

Result:

Single File



Allow only single file upload.

Code:
1
2
3
var myUploader = new SlashUploader (document.getElementById("my-uploader"), {
    maxFiles: 1
});

Result:

Progress Bar



Upload progress is seen with bar animation.

Code:
1
2
3
var myUploader = new SlashUploader (document.getElementById("my-uploader"), {
    progressAnimationType: "inline|bar"
});

Result:

Only Button



Don't show uploaded files or upload result.

Code:
1
2
3
var myUploader = new SlashUploader (document.getElementById("my-uploader"), {
    uploadedFilesPosition: "none"
});

Result:

With Validations & Limitations



The following example allows user to upload images files only. Each image width & hight must not exceed 400px. Each image size must not exceed 500KB.
Returned errors texts are also modified, to fit these limitations.
Error visability duration is set to 10 seconds.

Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var myUploader = new SlashUploader (document.getElementById("my-uploader"), {
    acceptOnlyFilesTypes: "image/*",
    allowedFilesExtensions: ["jpg", "jpeg", "bmp", "gif", "png"],
    allowedMaxFileSize: 500,
    customValidation: function (file) {
        if (file.width == null || file.height == null) {
            console.log ("Couldn't read metadata for '"+file.name+"', so dimensions validation isn't possible");
        } else if (file.width > 400 || file.height > 400) {
            return {
                error: "invalid_dimensions",
                error_text: "\"{{file_name}}\" width or height are bigger then 400px"
            };
        }
    },
    errors: {
        invalidFileExtension: "File \"{{file_name}}\" is not a supportted image format.",
        invalidFileSize: "File \"{{file_name}}\" exceeds 500KB."
    },
    displayErrorDuration: 10000
});

Result:

Disabled



Plugin is being disabled after user upload.

Code:
1
2
3
4
5
var myUploader = new SlashUploader (document.getElementById("my-uploader"), {
    onFilesUploaded: function (files) {
        this.disabled = true;
    }
});

Result:

Turned Off Options



No metadata for selected files.
No "Cancel" and no "Delete" buttons.
Drag & drop not allowed.
Show detailed error from server is disabled.
File list isn't cleaned up every time user selects files.
Default upload method is via Iframe (instead of stream or chunks)

Code:
1
2
3
4
5
6
7
8
9
var myUploader = new SlashUploader(document.getElementById("my-uploader"), {
	doGetFileMetadata: false,
	enableCancelButton: false,
	enableDeleteButton: false,
	enableDropFiles: false,
	showDetailedErrorFromServer: false,
	resetFilesOnEachUpload: false,
	uploadTypePriority: ["iframe", "stream", "chunks"]
});

Result:

Events



The following example uses events, and data is being sent to browser's console.

Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var myUploader = new SlashUploader (document.getElementById("my-uploader"), {
    onFilesSelected: function (files) {
        console.log ("onFilesSelected", files);
    },
    onFilesUploaded: function (files) {
        console.log ("onFilesUploaded");
        for (var i=0; i<files.length; i++) {
            var file = files[i];
            console.log (file);
        }
    },
    onFilesProgress: function (curUploadingFileProgress, curUploadingFileIndex, totalFilesToUpload) {
        var text = Math.floor(curUploadingFileProgress*100)+"%";
        text += " ("+(curUploadingFileIndex+1)+"/"+totalFilesToUpload+")";
        console.log ("onFilesProgress", text);
    },
    onCanceled: function () {
        console.log ("onCanceled");
    },
    onError: function (errors) {
        console.log ("onError", errors);
    },
    onFileDeleted: function (deletedFile, files) {
        console.log ("onFileDeleted", deletedFile, files);
    }
});

Result:

RTL



Display plugin with Right-to-Left direction, and with Hebrew translation.

Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var myUploader = new SlashUploader (document.getElementById("my-uploader"), {
    rtl: true,
    progressAnimationType: "inline|bar",
    browseText: "הנח קבצים כאן או לחץ כדי להעלות",
    browseTextDropDisabled: "לחץ כדי להעלות",
    cancelText: "ביטול",
    dropFilesText: "הנח קבצים כאן",
    uploadingFileByFileText: "מעלה את \"{{current_file_name}}\" (קובץ {{current_file_index}} מתוך {{total_files}})",
    uploadingFileText: "מעלה את הקובץ \"{{current_file_name}}\"...",
    uploadingFileTextProgressBar: "מעלה את הקובץ \"{{current_file_name}}\"...",
    uploadingFilesText: "מעלה {{total_files}} קבצים...",
    uploadingFilesTextProgressBar: "מעלה {{total_files}} קבצים...",
    errors: {
        invalidFileExtension: "סוג הקובץ \"{{file_name}}\" אינו נתמך",
        invalidFileSize: "הקובץ \"{{file_name}}\" שוקל יותר מדי",
        parseFailed: "פענוח המידע נכשל",
        unspecifiedError: "התרחשה שגיאה כללית",
        uploadFailed: "העלאת הקובץ נכשלה",
        networkError: "התרחשה תקלת תקשורת"
    }
});

Result:

Modified Style & Texts



CSS and texts changed. File name display is limited to 12 characters.

HTML Code:
1
<div id='my-uploader' class='custom_css'></div>
CSS Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
.custom_css .uploader_drop_area {
	border: 2px solid green;
	color: green;
}
.custom_css.hover .uploader_drop_area {
	background: #93c293;
	color: white;
}
.custom_css.dragged_enter .uploader_drop_area {
	background: #296d29;
	color: white;
	border: 2px dashed white;
}
.custom_css.dragged_over .uploader_drop_area {
	background: #0c510c;
	color: white;
	border: 2px dashed white;
}
.custom_css.uploading .uploader_text span {
	font-weight: bold;
}
.custom_css .uploader_drop_area_bottom {
	background: #97e497;
}
.custom_css .uploader_spinner {
    border: 2px solid green;
    border-right: 2px solid rgba(0, 255, 0, 0.25);
    border-bottom: 2px solid rgba(0, 255, 0, 0.25);
    border-left: 2px solid rgba(0, 255, 0, 0.25);
}
.custom_css .uploader_result_file a {
	color: green;
}
.custom_css .uploader_progress_container .uploader_progress_bar>div>div {
	background: green;
}
JS Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var myUploader = new SlashUploader (document.getElementById("my-uploader"), {
    progressAnimationType: "inline|bar",
    maxFileChars: 12,
    browseText: "Drop or click",
    browseTextDropDisabled: "Click here",
    cancelText: "Abort!",
    dropFilesText: "Drop files",
    uploadingFileByFileText: "Uploading {{current_file_index}}/{{total_files}} (\"{{current_file_name}}\")",
    uploadingFileText: "Uploading \"{{current_file_name}}\"...",
    uploadingFileTextProgressBar: "Uploading \"{{current_file_name}}\"...",
    uploadingFilesText: "Uploading {{total_files}} files...",
    uploadingFilesTextProgressBar: "Uploading {{total_files}} files...",
    errors: {
        invalidFileExtension: "\"{{file_name}}\" - invalid extenstion",
        invalidFileSize: "\"{{file_name}}\" - invalid size",
        parseFailed: "Error parsing data",
        unspecifiedError: "Error occurred",
        uploadFailed: "Error on server",
        networkError: "Network error"
    },
    uploadedFileHtml: "• <a href='{{current_file_path}}' target='_blank'>{{current_file_name}}</a>"
});

Result:

Custom Element



Use of custom HTML element, without changing its layout and style.

HTML Code:
1
2
3
4
<div id="my-uploader" class="custom_html">
	Click to upload!
</div>
<button type="button" onclick="myUploader.cancelUpload();">Cancel</button>
CSS Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
.custom_html {
	width: 120px;
	height: 60px;
	border: 2px solid red;
	transition: all 0.5s;
	-webkit-transition: all 0.5s;
}
.custom_html.hover {
	background-color: tomato;
}
.custom_html.dragged_enter {
	border: 2px dashed red;
	background-color: white;
}
.custom_html.dragged_over {
	border: 2px dashed tomato;
	background-color: #ffcaca;
}
.custom_html.uploading {
	opacity: 0.5;
}
JS Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var myUploader = new SlashUploader (document.getElementById("my-uploader"), {
    customHTML: true,
    onFilesSelected: function (files) {
        console.log ("onFilesSelected", files);
    },
    onFilesUploaded: function (files) {
        var text = "Uploaded "+files.length+" files:\n\n"
        for (var i=0; i<files.length; i++) {
            var file = files[i];
            text += (i+1)+". ";
            text += "Name: "+file.file_name+"; ";
            text += "URL: "+file.file_path+";\n\n";
        }
        console.log (text);
        alert (text);
    },
    onFilesProgress: function (curUploadingFileProgress, curUploadingFileIndex, totalFilesToUpload) {
        var text = Math.floor(curUploadingFileProgress*100)+"% ("+(curUploadingFileIndex+1)+"/"+totalFilesToUpload+")";
        console.log (text);
    },
    onCanceled: function () {
        console.log ("Canceled");
    },
    onError: function (errors) {
        console.log ("onError", errors);
    }
});

Result:
Click to upload!

Installation



Download the SlashUploader pack, and include SlashUploader.js and SlashUploader.css files in your HTML:
1
2
<script src='./SlashUploader/SlashUploader.min.js'></script> 
<link href='./SlashUploader/SlashUploader.min.css' type='text/css' rel='stylesheet'>

Usage



Create empty DIV in your HTML page:
1
<div id='my-uploader' style='width: 600px; height: 80px;'></div>

And define SlashUploader instance on that DIV, with default settings:
1
var myUploader = new SlashUploader (document.getElementById("my-uploader"));

Or with modified configurations:
1
2
3
4
var myUploader = new SlashUploader (document.getElementById("my-uploader"), {
    maxFiles: 3,
    rtl: true
});

SlashUploader uses Iframe gateway, to support cross-domain uploads on browsers with strict security policy, or very old browsers. To support that ability, make sure you set the correct path to the "iframe_gateway.html" file:
1
myUploader.iframeGateway = "./SlashUploader/iframe_gateway.html";

And make sure your server can handle files upload requests, as explained below.

Server-Side



SlashUploader is a client-side plugin. In order to upload files to a server you would need, of course, server-side files to handle these requests.
If you download the SlashUploader pack, you can find an example C# .NET file to handle upload requests. If your server does not support .NET, make sure to build your own server-side files, with 3 endpoints as described below.


Plugin Settings


To set server endpoints, define your server-side scripts within the plugin serverScripts parameter:
1
2
3
4
5
6
7
8
myUploader.serverScripts = {
    uploadChunk: "http://mydomain.com/chunk_upload.php?file_name={{file_name}}&chunk_index={{chunk_index}}&total_chunks={{total_chunks}}&request_id={{request_id}}&rotation={{rotation}}",
    uploadStream: "http://mydomain.com/stream_upload.php?file_name={{file_name}}&rotation={{rotation}}",
    uploadThroughIframe: "http://mydomain.com/iframe_upload.php?request_id={{request_id}}&iframe_gateway={{iframe_gateway}}&rotation={{rotation}}",
    fileNameVariableName: "file_name",
    fileUrlVariableName: "file_path",
    errorVariableName: "error"
};


Server Returned Data Structure


The server should return JSON (and should support JSONP for cross-domain ability) with array of objects. Each object contains uploaded file data - name and URL - with variable names as defined in the plugin serverScripts.fileNameVariableName (default: "file_name") and serverScripts.fileUrlVariableName (default: "file_path"). If error occurred on server, object should contain error string, within a varaiable named as serverScripts.errorVariableName value (default: "error").

Example response from server:

1
2
3
4
5
6
7
8
9
10
[{
    "file_name": "1.jpg",
    "file_path": "http://mydomain.com/uploads/1.jpg",
    "error": ""
},
{
    "file_name": "file.mp4",
    "file_path": "http://mydomain.com/uploads/file.mp4",
    "error": ""
}]


Server Endpoints


For best performance, SlashUploader decides how to upload the files - using chunked upload, using stream file read, or posting file through Iframe. That decision is based on the settings you give the plugin and on the current user's browser capabilities.
Therefore, to handle SlashUploader requests to server, your server scripts should have these three following endpoints:

1. Upload Chunk - If the plugin uses chunks upload (based on given settings and user's browser abilities), it devides the selected file into small chunks and send these chunks one after the other.
For each chunked upload, a small part of the file is being uploaded to the server. The server script should recieve this chunk and save it in a folder.
When all chunks were uploaded, they should combine back into a single file.

2. Upload Stream - Based on given settings and user's browser abilities, the plugin might upload the file as stream.

3. Upload Through Iframe - Based on given settings and user's browser abilities, the plugin might upload the file using an Iframe gateway.
A server script should receive posted file data and save it as a file.
In this case, response from the server should not be a plain JSON, but a string - the result JSON should be URL encoded, wrapped inside the followig HTML string:

1
"<html><body><iframe src='" + IframeGateway + "?request_id=" + RequestId + "&data=" + UrlEncodedJson + "' id='gateway_iframe' style='width: 1px; height: 1px; opacity: 0; display: none;'></iframe></body></html>"

The script's parameters are:
IframeGateway - Path of the iframe gateway (as recived from {{iframe_gateway}} parameter on serverScripts.uploadThroughIframe URL).
RequestId - Current request unique ID (as recived from {{request_id}} parameter on serverScripts.uploadThroughIframe URL).
UrlEncodedJson - Result JSON array, made into URL encoded string.

For example, response text would look like this:
1
<html><body><iframe src='http://mydomain.com/uploader/iframe_gateway.html?request_id=811035872&data=%5b%7b%0d%0a%09%09%09%22file_name%22%3a+%221.png%22%2c%0d%0a%09%09%09%22file_path%22%3a+%22%2f%2fmydomain.com%2fuploader%2fuploads%2f1.png%22%2c%0d%0a%09%09%09%22error%22%3a+%22%22%0d%0a%09%09%09%7d%2c%7b%0d%0a%09%09%09%22file_name%22%3a+%22video.mp4%22%2c%0d%0a%09%09%09%22file_path%22%3a+%22%2f%2fmydomain.com%2fuploader%2fuploads%2fvideo.mp4%22%2c%0d%0a%09%09%09%22error%22%3a+%22%22%0d%0a%09%09%09%7d%5d' id='gateway_iframe' style='width: 1px; height: 1px; opacity: 0; display: none;'></iframe></body></html>


Plugin Additional Parameters


SlashUploader can send some additional parameters to the server, of the file meta data (depending on file type and browser capability).
Each parameter can be used in the upload script, with opening double curly brackets "{{" and closing double curly brackets "}}".

These parameters are:
{{file_name}} - File name.
{{size}} - File size, in KB.
{{roation}} - Image rotation, in degrees. Based on camera orientation when the picture was capruted.
{{duration}} - Media file duration, in seconds.
{{width}} - Image or video file width, in pixels.
{{height}} - Image or video file height, in pixels.
{{extension}} - File extension.

Example use:
1
myUploader.serverScripts.uploadStream = "http://mydomain.com/stream_upload.php?file_name={{file_name}}&file_size={{size}}&file_rotation={{rotation}}&file_duration={{duration}}&file_w={{width}}&file_h={{height}}&file_ext={{extension}}";


Important Issues


• Make sure that your "uploads" folder on the server has read & write permissions.
• It's highly important to secure the folder users can upload files to - allow only file types necessary for your application functionality, perform filtering and content checking on uploaded file, ect. More information regarding that vulnerability can be found here.


Compatibility



SlashUploader offers plenty of features on a varaiaty of browsers, including very old browsers such as IE8.

For some features there is no workaround on old browsers, but SlashUploader provides fallbacks for these browsers. The following table shows what are the supported functionalities for each browser. But anyway, since SlashUploader provides fallbacks, all users will be able to have the basic upload functionality.

Notice that for some features there is a distinction between an implantation of SlashUploader plugin using a server script on a remote server (cross-domain), and using a server script on the same domain where plugin is displayed.


Chrome / Firefox

Safari

Edge

Safari on iPhone

Chrome on Android

IE 10 / 11

IE 8-9
Click to upload Same-Domain
Cross-Domain
Drag & Drop to upload Same-Domain
Cross-Domain
Upload multiple files at once
Get file metadata

?

Image preview on upload
File type validation
File size validation
Custom file validation
Limit file type selection
Upload in chunks Same-Domain
Cross-Domain
Progress indication (with chunked upload) Same-Domain
Cross-Domain
Progress indication (without chunked upload) Same-Domain

?

Cross-Domain
Modify plugin texts
Modify plugin CSS
Use custom design
Cancel upload
Disable / Enbale user interaction
Pre-define uploaded files
Right-to-left support
Show uploaded files
Trigger plugin events

Options



Modified configuration can be defined on initialization:
1
2
3
4
var myUploader = new SlashUploader (document.getElementById("my-uploader"), {
    maxFiles: 3,
    rtl: true
});

Or at run-time, after initialization:
1
2
3
var myUploader = new SlashUploader (document.getElementById("my-uploader"));
myUploader.maxFiles = 3;
myUploader.rtl = true;

The following table provides a list of functionality configuration options avaliable in SlashUploader:

Option Type Description
acceptOnlyFilesTypes
default: null
String Defines the input "accept" attribute, allowing the user to select only certin file types.
Avaliable values can be "image/*" (to allow only images files selection such as JPG or PNG), "video/*" (to allow only video files selection), "text/html" (to allow user to select only HTML files), ".csv, application/vnd.ms-excel" (to allow only specific excel files), ect.
Demo here.
allowedFilesExtensions
default: null
Array Files extenstions list to validate.
If the array is populated and contains a list of files extenstions, the plugin would validate the file extension upon file selection.
If each selected files matches one of the array memebers, files can be uploaded. If not, "invalid_file_extension" error is thrown.
For example:
1
myUploader.allowedFilesExtensions = ["mp4", "mov"];
Demo here.
allowedMaxFileSize
default: null
Number Maximum allowed file size, in KB (1 KB = 1/1000 MB).
If the variable is populated with value bigger then 0, the plugin would validate the file size upon file selection.
If each selected files size is less then given value, files can be uploaded. If not, "invalid_file_size" error is thrown.
For example:
1
myUploader.allowedMaxFileSize = 1000;
Demo here.
capture
default: null
String Force the use of a specific media element to upload the file from.
Avaliable values are -
camera - Capture media directly from the device's camera.
camcorder - Capture media directly from the device's video camera.
microphone - Capture media directly from the device's microphone.
filesystem - Capture media directly from the device's gallery.
user - Capture media directly from the user-facing camera and/or microphone.
environment - Capture media directly from the outward-facing camera and/or microphone.
customHTML
default: false
Boolean If value is set to true, the plugin is being wraped under the selected DOM element. So the element is receiving the SlashUploader functionality and events, without changing its layout and design.
customHTML option can be declared only at initialization.
For example:
1
2
3
var myUploader = new SlashUploader (document.getElementById("my-uploader"), {
	customHTML: true
});
Demo here.
customValidation
default: null
Function Validating with a custom function upon files selection. In case of an error, function should return a custom error object.
For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
myUploader.customValidation = function (file) {
    if (file.duration == null) {
        console.log ("Couldn't read metadata for '"+file.name+"'");
        // Could not get file metadata, so validating it isn't possible
    } else if (file.duration < 10) {
        return {
            error: "invalid_duration",
            error_text: "'{{file_name}}' is less then 10 seconds"
        };
        // File is not valid
    } else {
        // File is valid
    }
}
Demo here.
disabled
default: false
Boolean If value is set to true, user interaction is disabled.
Demo here.
displayErrorDuration
default: 4500
Number Amount of time, in milliseconds, to display validation errors before hiding them.
Demo here.
doGetFileMetadata
default: true
Boolean Determines if plugin would try to recieve files metadata upon selection.
Reading the file metadata might get heavy on the browser, if the file is big. So if there's no use for that option, better set it to false.
SlashUploader plugin can get the following metadata for each file (as long as the user's browser provides the ability - have a look at the "Compatibility" table):
file - native file object.
name - file name.
extension - file extension.
type - file type.
size - file size, in KB.
duration - media file length in seconds.
width - image / video file width in pixels.
height - image / video file height in pixels.
rotation - image rotation, based on the camera orientation when the picture was captured.
enableCancelButton
default: true
Boolean Determines if plugin shows or hides the "Cancel" button while uploading file.
Demo here.
enableDeleteButton
default: true
Boolean Determines if plugin shows or hides the "Delete" button (after file or files were successfully uploaded) next to each uploaded file.
Demo here.
enableDropFiles
default: true
Boolean Determines if drag & drop ability is allowed. If false, only click ability is allowed to select files.
Demo here.
fileSizeToForceChunksUpload
default: 500000
Number If one or more of the selected files size was larger then the value of fileSizeToForceChunksUpload (in KB), upload type is determined to be chunks upload (on browsers where possible) instead of stream upload.
groupedUploadedFilesHtml
default:
{{total_files}} files uploaded
String HTML template to display the uploaded files, if groupUploadedFilesResult is set to true.
groupUploadedFilesResult
default: false
Boolean If value set to true, then uploaded files results appear in one, combined row (using the template text of groupedUploadedFilesHtml parameter), instead of showing each uploaded file in its own row.
height
default: 80
String Determines the height of the componenet, in pixels.
iframeGateway
default: SlashUploader/iframe_gateway.html
String Determines the relative location of "iframe_gateway.html" file. Iframe gateway is used as a fallback for browsers that have a strict cross-domain policy (such as Safari) or are just very old (such as IE 9).
maxFileChars
default: 20
Number Maximum characters length to display for a file name. Upon selection or upload of a file, its name is being displayed, and if the file name length is more then the given value - file name is being trimmed to the given value length.
Demo here.
maxFiles
default: 9999
Number Maximum amount of files to enable the user to upload.
Demo here.
progressAnimationType
default: inline
String Files upload progress indication type.
Can have one of the following values:
null - No progress animation is being displayed.
inline - Progress animation is displayed inside the button itself. If an image is selected, the preview of the image is seen within the animation.
bar - Progress bar animation is displayed with a filling bar.

Value can also include two types with a "|" (vertical bar) separator.
For example:
1
myUploader.progressAnimationType = "inline|bar";
Demo here.
resetFilesOnEachUpload
default: true
Boolean Determines if files list is being cleaned up every time user selects files (if value is true), or files list is kept and new files are added to the list (if value is false).
retryTimeout
default: 1500
Number When chunk was not uploaded successfully and an error was returned from the server, the plugin retries to upload the same chunk again.
The value of retryTimeout determines how much time to wait (in milliseconds) between each such try.
retryTimes
default: 10
Number When chunk was not uploaded successfully and an error was returned from the server, the plugin retries to upload the same chunk again.
The value of retryTimes determines how many times to retry uploading the same chunk, before sending showing an error message.
rtl
default: false
Boolean If true, plugin is displayed in right-to-left direction. Useful for right-to-left languages such as Hebrew or Arabic.
Demo here.
serverScripts
default: Click here
Object Object containing server scripts URLs, for which the plugin uploads the files to.

The object contains the following variables:
uploadChunk - Script to upload file chunk, if chunks upload is being used. On last chunk, script should combine all chunks back into a single file.
uploadStream - Script to upload file as stream, if stream upload is being used.
uploadThroughIframe - Script to upload file using Iframe gateway, if Iframe upload is being used.
fileNameVariableName - File name variable to expect back from server, for a successful upload.
fileUrlVariableName - File URL variable to expect back from server, for a successful upload.
errorVariableName - Error variable to expect back from server, if server script failed.

For example:
1
2
3
4
5
6
7
8
myUploader.serverScripts = {
    uploadChunk: "http://mydomain.com/chunk_upload.php?file_name={{file_name}}&chunk_index={{chunk_index}}&total_chunks={{total_chunks}}&request_id={{request_id}}&rotation={{rotation}}",
    uploadStream: "http://mydomain.com/stream_upload.php?file_name={{file_name}}&rotation={{rotation}}",
    uploadThroughIframe: "http://mydomain.com/iframe_upload.php?request_id={{request_id}}&iframe_gateway={{iframe_gateway}}&rotation={{rotation}}",
    fileNameVariableName: "file_name",
    fileUrlVariableName: "file_path",
    errorVariableName: "error"
};

The server should return JSON (and should support JSONP for cross-domain ability) with array of objects. Each object contains uploaded file data - name and URL - with variable names as defined in serverScripts.fileNameVariableName and serverScripts.fileUrlVariableName. If error occurred on server, object should contain error description, within a varaiable named as serverScripts.errorVariableName value.

Example response from server:
1
2
3
4
5
6
7
8
9
10
[{
    "file_name": "1.jpg",
    "file_path": "http://mydomain.com/uploads/1.jpg",
    "error": ""
},
{
    "file_name": "file.mp4",
    "file_path": "http://mydomain.com/uploads/file.mp4",
    "error": ""
}]

SlashUploader can send some additional parameters to the server, of the file meta data (depending on file type and browser capability).
These parameters are:
{{file_name}} - File name.
{{size}} - File size, in KB.
{{roation}} - Image rotation, in degrees. Based on camera orientation when the picture was capruted.
{{duration}} - Media file duration, in seconds.
{{width}} - Image or video file width, in pixels.
{{height}} - Image or video file height, in pixels.
{{extension}} - File extension.
Example use:
1
myUploader.serverScripts.uploadStream = "http://mydomain.com/stream_upload.php?file_name={{file_name}}&file_size={{size}}&file_rotation={{rotation}}&file_duration={{duration}}&file_w={{width}}&file_h={{height}}&file_ext={{extension}}";

Detailed information about how to write server-side files can be seen here.
showDetailedErrorFromServer
default: true
Boolean Determines if detailed error from server should be seen in case such error occured, or the general text should be displayed as defined on errors.uploadFailed parameter.
Demo here.
showFocusRect
default: false
Boolean Determines if a rectangle should be displayed when SlashUploader componenet is focused.
status
default: idle
String Returns current state of the uploader insance.

Can be one of the following values:
idle - No files to upload were yet selected.
uploading - Files to upload were selected and are currently in upload progress.
uploaded - Uploading the files finished succesfuly.
canceled - Uploading proccess was canceled.
error - There was an error uploading the selected files.

Example use:
1
console.log (myUploader.status);
uploadedFileHtml
default:
<a href='{{current_file_path}}' target='_blank'>{{current_file_name}}</a>
String HTML template to display the uploaded files.
Example use:
1
myUploader.uploadedFileHtml = "<img src='{{current_file_path}}' title='{{current_file_name}}' height='40' />";
Demo here.
uploadedFilesPosition
String Determines where uploaded files links should be displayed, relatively to the upload button.
Avaliable values are:
default - Disaply uploaded files beside the button on desktop browsers and below the button on mobile browsers.
none - Don't display show uploaded files.
below - Display uploaded files beside the button.
beside - Display uploaded files below the button.
Demo here.
uploadedFileTemplate
default: null
Function Template callback function to display the uploaded file.
The function receives one parameter -
• If groupUploadedFilesResult is set to false (default behavior) - the parameter is an object, contains the file name and URL as returned from server.
• If groupUploadedFilesResult is set to true - the parameter is an array of objects, each object contains the file name and URL as returned from server.

Example Use:
1
2
3
4
5
6
7
myUploader.uploadedFileTemplate = function (fileData) {
    if (fileData.file_name.toLowerCase().indexOf(".jpg") != -1 || fileData.file_name.toLowerCase().indexOf(".png") != -1) {
        return "<img src='"+fileData.file_path+"' height='40' />";
    } else {
        return "<a style='font-weight: bold;' href='"+fileData.file_path+"' target='_blank'>"+fileData.file_name+"</a>";
    }
}
uploadedFiles
default: null
Array Gets or sets the current files list that was uploaded.
The array contains list of objects, each object containing file name (parameter file_name) and URL (parameter file_path).
This option can be used to receive user's uploaded files data, to pre-define the uploaded files list, or to define at run-time the uploaded files list.
For example:
1
2
3
4
5
6
7
// Get
console.log (myUploader.uploadedFiles);
// Set
myUploader.uploadedFiles = [
    {file_name: "1.jpg", file_path: "http://mydomain.com/uploads/1.jpg"},
    {file_name: "video.mp4", file_path: "http://mydomain.com/uploads/video.mp4"}
];
uploadTypePriority
default: ["stream", "chunks", "iframe"]
Array Determines the wanted upload type (stream / chunks / iframe) priority the plugin would try to upload files with.
The avaliable upload types are depend on the user's browser support and abilities. The order in which the plugin would try to upload is the order of the given uploadTypePriority array.
For example, if the user's browser is Safari and the upload server script is on another domain - uploading using chunks or stream is not possible. So for the given uploadTypePriority value of ["chunks", "stream", "iframe"], the plugin would upload files using iframe.
Example Use:
1
myUploader.uploadTypePriority = ["chunks", "stream", "iframe"];
value
default: null
Array Gets or sets the current files list that was uploaded - as described on uploadedFiles.
For example:
1
2
3
4
5
6
7
// Get
console.log (myUploader.value);
// Set
myUploader.value = [
    {file_name: "1.jpg", file_path: "http://mydomain.com/uploads/1.jpg"},
    {file_name: "video.mp4", file_path: "http://mydomain.com/uploads/video.mp4"}
];

Texts



In order to translate the plugin, or just to use your own texts, all plugin texts are configurable.
The following table provides a list of texts configuration options avaliable in SlashUploader.
Demos showing use of the plugin with modified text can be seen here and here.

Option Default value Description
browseText "Drop files here or click to upload" Displayed on: Upload button.
When: Before and after upload.
Condition: Drag & drop is enabled.
browseTextDropDisabled "Click to upload" Displayed on: Upload button.
When: Before and after upload.
Condition: Drag & drop is disabled.
cancelText "Cancel" Displayed on: Cancel button.
When: While uploading.
dropFilesText "Drop files here" Displayed on: Upload button.
When: File is being dragged to the browser window.
Condition: Drag & drop is enabled.
errors.invalidFileExtension "Invalid file extension ({{file_name}})" Displayed on: Upload result.
When: After selecting files.
Condition: One or more of selected files are not valid due to wrong file extension.
errors.invalidFileSize "Invalid file size ({{file_name}})" Displayed on: Upload result.
When: After selecting files.
Condition: One or more of selected files are not valid due to wrong file size.
errors.networkError "Network error" Displayed on: Upload result.
When: After sending upload request to server.
Condition: Network error occurred when trying to upload files to server.
errors.parseFailed "Failed to parse result" Displayed on: Upload result.
When: After sending upload request to server.
Condition: Json returned from server is malformed and not parsable.
errors.unspecifiedError "Unspecified error" Displayed on: Upload result.
When: After selecting files or after sending upload request to server.
Condition: One or more of selected files didn't passed validation of customValidation, or upload failed on server, and no serverScripts.errorVariableName was returned.
errors.uploadFailed "Failed to upload" Displayed on: Upload result.
When: After sending upload request to server.
Condition: Upload failed on server.
groupedUploadedFilesHtml "{{total_files}} files uploaded" Displayed on: Upload result.
When: After uploading.
Condition: File or files were uploaded successfully, and groupUploadedFilesResult is set to true.
uploadedFileHtml "<a href='{{current_file_path}}' target='_blank'>{{current_file_name}}</a>" Displayed on: Upload result.
When: After uploading.
Condition: File or files were uploaded successfully.
Example use:
1
myUploader.uploadedFileHtml = "<img src='{{current_file_path}}' title='{{current_file_name}}' height='40' />";
Demo here.
uploadingFileByFileText "Uploading \"{{current_file_name}}\" ({{current_file_index}}/{{total_files}})" Displayed on: Upload button.
When: While uploading.
Conditions:
• User selected serveral files to upload at once.
• Upload method is "Chunks" or "Stream".
uploadingFileText "Uploading \"{{current_file_name}}\"" Displayed on: Upload button.
When: While uploading.
Condition: User selected a single file to upload.
uploadingFileTextProgressBar "Uploading \"{{current_file_name}}\"" Displayed on: Progres bar (if progressAnimationType = "bar").
When: While uploading.
Condition: User selected a single file to upload.
uploadingFilesText "Uploading {{total_files}} files" Displayed on: Upload button.
When: While uploading.
Conditions:
• User selected serveral files to upload at once.
• Upload method is "through iframe" (due to given settings or lack of browser capability).
uploadingFilesTextProgressBar "Uploading {{total_files}} files" Displayed on: Progres bar (if progressAnimationType = "bar").
When: While uploading.
Condition: User selected multiple files at once to upload.

Styles



SlashUploader allows you to change its CSS style or to use your own existing DOM element with its own design and layout.
Styled plugin demo can be seen here. Custom HTML element demo can be seen here.

For example, to change the plugin color to green, you can give the following CSS to your SlashUploader element:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
.custom_css .uploader_drop_area {
	border: 2px solid green;
	color: green;
}
.custom_css.hover .uploader_drop_area {
	background: #93c293;
	color: white;
}
.custom_css.dragged_enter .uploader_drop_area {
	background: #296d29;
	color: white;
	border: 2px dashed white;
}
.custom_css.dragged_over .uploader_drop_area {
	background: #0c510c;
	color: white;
	border: 2px dashed white;
}
.custom_css.uploading .uploader_text span {
	font-weight: bold;
}
.custom_css .uploader_drop_area_bottom {
	background: #97e497;
}
.custom_css .uploader_spinner {
	border: 2px solid green;
	border-right: 2px solid rgba(0, 255, 0, 0.25);
	border-bottom: 2px solid rgba(0, 255, 0, 0.25);
	border-left: 2px solid rgba(0, 255, 0, 0.25);
}
.custom_css .uploader_result_file a {
	color: green;
}
.custom_css .uploader_progress_container .uploader_progress_bar>div>div {
	background: green;
}

Or, if you want to use your own DOM element with its own layout and style, you can set the customHTML parameter to true.
Custom HTML element demo can be seen here.

For example, if this is your element:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<html>
<head>
    <style>
	#custom_html {
		width: 120px;
		height: auto;
		border: 2px solid red;
		transition: all 0.5s;
		-webkit-transition: all 0.5s;
	}
	#custom_html.hover {
		background-color: tomato;
	}
	#custom_html.dragged_enter {
		border: 2px dashed red;
		background-color: white;
	}
	#custom_html.dragged_over {
		border: 2px dashed tomato;
		background-color: #ffcaca;
	}
	#custom_html.uploading {
		opacity: 0.5;
	}
    </style>
</head>
<body>
    <div id="custom_html">
        Upload now!
    </div>
</body>
</html>


Simpley initialize SlashUploader instance with customHTML parameter set to true:
1
2
3 4
5
6
var myUploader = new SlashUploader (document.getElementById("custom_html"), {
	customHTML: true,
	onFilesUploaded: function (files) {
		console.log (myUploader.uploadedFiles);
	}
});

Events




The following table provides a list of events triggered by SlashUploader.
Events demo can be seen here.

Option Type Description
onCanceled
default: null
Function Triggered when "Cancel Upload" button was clicked by the user.
For example:
1
2
3
myUploader.onCanceled = function () {
    console.log ("Canceled");
};
onError
default: null
Function Triggered when validation error or server error occurred.

Parameters:
errors - Array of errors, each error contains parameters:
file - File object.
error - Type of error. can be invalid_file_extension, invalid_file_size or upload_failed.
error_object - Error additional data.

For example:
1
2
3
myUploader.onError = function (errors) {
    console.log (errors);
};
onFileDeleted
default: null
Function Triggered when user clicked the "Delete" icon for a speific file, on "Upload Results" section.

Parameters:
deletedFile - File object of the deleted file.
files - Array containing files objects of the ramining files that weren't deleted.

For example:
1
2
3
4
myUploader.onFileDeleted = function (deletedFile, files) {
    console.log ("Deleted file:", deletedFile);
    console.log ("Remaining files:", files);
};
onFilesProgress
default: null
Function Triggered during file upload progress.

Parameters:
curUploadingFileProgress - Progress of current file being uploaded, from 0 to 1.
curUploadingFileIndex - Index of current file being uploaded, when first is 0.
totalFilesToUpload - Amount of total files selected by the user to upload.

For example:
1
2
3
4
myUploader.onFilesProgress = function (curUploadingFileProgress, curUploadingFileIndex, totalFilesToUpload) {
    var text = "Uploaded "+Math.floor(curUploadingFileProgress*100)+"% (file "+(curUploadingFileIndex+1)+"/"+totalFilesToUpload+")";
    console.log (text);
};
onFilesSelected
default: null
Function Triggered when user selected files to upload.
Notice that if the function defines "continueUpload" argument, the "continueUpload" function must be triggered in order to continue with the uploading proccess.

Parameters:
files - Array of files object, with each object containg:
file - Native file object.
name - File name.
extension - File extension.
type - File type.
size - File size, in KB.
width - File width in pixels, if selected file is image or video.
height - File height in pixels, if selected file is image or video.
duration - Media file length in seconds.
rotation - Image rotation, based on the camera orientation when the picture was captured.
continueUpload - If defined, function must be triggered in order to continue with the uploading proccess.

For example:
1
2
3
myUploader.onFilesSelected = function (files) {
    console.log (files);
};
Example use of "continueUpload" argument:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
myUploader.onFilesSelected = function(files, continueUpload) {
    console.log (files);
    // Upload is now stopped, waiting for "continueUpload" function to be called
    $.ajax({
        url: "https://mydomain.com/test_files.php",
        data: {selected_files: JSON.stringify(files)},
        success: function (response) {
            if (response.success) {
                continueUpload(); // Upload now continues
            } else {
                this.cancelUpload(); // Cancel current file upload
            }
        }
    });
}
onFilesUploaded
default: null
Function Triggered when files were uploaded and a successful response was retuned from server.

Parameters:
files - Array of files object, with each object containg:
file_name - File name.
file_path - File URL.
For example:
1
2
3
4
5
6
7
8
myUploader.onFilesUploaded = function (files) {
    for (var i=0; i<files.length; i++) {
        var file = files[i];
        console.log ("File number "+(i+1));
        console.log ("Name: "+file.file_name);
        console.log ("URL: "+file.file_path);
    }
};

Functions




The following functions can be used on a SlashUploader instance:

Option Type Description
cancelUpload Function Cancels the current file upload.
For example:
1
myUploader.cancelUpload();
destroy Function Remove and cleans all created DOM and events.
For example:
1
myUploader.destroy();






Credits & Contact



This plugin was made by Slash Apps Development, development company based in Tel-Aviv. We plan, design and develop beautiful web & mobile apps, websites, games and data-management systems.

Along our work over the years, we used many plugins and libraries. This plugin is our way of giving back to the community :)

Feel free to contact us, regarding this plugin or any other issue:
Contact us:






License



SlashUploader plugin is licensed under MIT.