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

Ver 1.5.1

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: 200px;'></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"), {
    showUploadedFiles: false
});

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 chunks upload.
No metadata for selected files.
Drag & drop not allowed.
Show detailed error from server is disabled.
And file list isn't cleaned up every time user selects files.

Code:
1
2
3
4
5
6
7
var myUploader = new SlashUploader (document.getElementById("my-uploader"), {
    uploadFileInChunks: false,
    doGetFileMetadata: false,
    enableDropFiles: false,
    showDetailedErrorFromServer: false,
    resetFilesOnEachUpload: false
});

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
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}}\" שוקל יותר מדי",
        unspecifiedError: "התרחשה שגיאה כללית",
        uploadFailed: "העלאת הקובץ נכשלה"
    }
});

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
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",
        unspecifiedError: "Error occurred",
        uploadFailed: "Error on server"
    },
    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[this.serverScripts.fileNameVariableName]+"; ";
            text += "URL: "+file[this.serverScripts.fileUrlVariableName]+";\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: 200px;'></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";

Server-Side



SlashUploader is a client-side plugin. To upload files to 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 4 endpoints as described below.
You would also need to 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.

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

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 the following endpoints:

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.

Combine Chunks - When all chunks were uploaded, a request is sent to a script that takes all chunks and combine them back into a single file.
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.error (default: "error") value.

Example response from server:

1
2
3
4
5
6
7
8
9
[{
    "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": ""
}]


Upload Stream - Based on given settings and user's browser abilities, the plugin might upload the file as stream.
A server script should receive that stream data, save it as a file in a folder, and return JSON (or JSONP) as described on the previous Combine Chunks endpoint.

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, save it as a file in a folder, and return url encoded JSON within HTML string.
The JSON structure should be the same as previously described endpoints - Combine Chunks and Upload Stream. Then the complete JSON string should be url encoded. And the encoded value should be returned wraped 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 a complete url encoded string, as explained above.

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>


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 tables 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 11

IE 10

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
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
Limit file type selection
Trigger "selected" event
Trigger "uploaded" event
Trigger "progress" event
Trigger "deleted" event
Trigger "canceled" event
Trigger "error" event

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.
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 miliseconds, 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 oriantation when the picture was captured.
enableDropFiles
default: true
Boolean Determines if drag & drop ability is allowed. If false, only click ability is allowed to select files.
Demo here.
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: 22
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).
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 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.
combineChunks - Script to combine chunks back to a file, if chunks upload is being used.
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
9
myUploader.serverScripts = {
    uploadChunk: "http://mydomain.com/chunk_upload.php?file_name={{file_name}}&chunk_index={{chunk_index}}&request_id={{request_id}}",
    combineChunks: "http://mydomain.com/combine_chunks.php?rotation={{rotation}}&file_name={{file_name}}&request_id={{request_id}}",
    uploadStream: "http://mydomain.com/stream_upload.php?rotation={{rotation}}&file_name={{file_name}}",
    uploadThroughIframe: "http://mydomain.com/iframe_upload.php?rotation={{rotation}}&request_id={{request_id}}&iframe_gateway={{iframe_gateway}}",
    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.error 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": ""
}]
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.
showUploadedFiles
default: true
Boolean Determines if uploaded files links should be displayed (true) or just a button should be displayed (false).
Demo here.
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.
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 (with a variable name as serverScripts.fileNameVariableName) and URL (with a variable name as serverScripts.fileUrlVariableName).
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"}
];
uploadFileInChunks
default: true
Boolean Determines if plugin would try to upload files in chunks, if user's browser support such ability.

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.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.
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.

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 oriantation when the picture was captured.
For example:
1
2
3
myUploader.onFilesSelected = function (files) {
    console.log (files);
};
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:
serverScripts.fileNameVariableName - File name.
serverScripts.fileUrlVariableName - 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[this.serverScripts.fileNameVariableName]);
        console.log ("URL: "+file[this.serverScripts.fileUrlVariableName]);
    }
};

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();






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.