jQuery

jQuery File Upload Example

The aim of this example is to give you the right knowledge about how you can achieve file upload with jQuery. Notice that this is not an easy task, and plugins are recommended to have non-surprising results.

In particular, there is one famous and very used jQuery Plugin for file upload made public to GitHub by blueimp. They created a file upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video for jQuery.

It supports cross-domain, chunked and resumable file uploads. Works with any server-side platform (Google App Engine, PHP, Python, Ruby on Rails, Java, etc.) that supports standard HTML form file uploads.
 

1. Plugin Demo and Features

1.1 Video Demo #1 – Single & Multiple Files Upload

1.2 Video Demo #2 – Drag & Drop File Upload

1.3 Features

• Multiple file upload:
Allows to select multiple files at once and upload them simultaneously.
• Drag & Drop support:
Allows to upload files by dragging them from your desktop or filemanager and dropping them on your browser window.
• Upload progress bar:
Shows a progress bar indicating the upload progress for individual files and for all uploads combined.
• Cancelable uploads:
Individual file uploads can be canceled to stop the upload progress.
• Resumable uploads:
Aborted uploads can be resumed with browsers supporting the Blob API.
• Chunked uploads:
Large files can be uploaded in smaller chunks with browsers supporting the Blob API.
• Client-side image resizing:
Images can be automatically resized on client-side with browsers supporting the required JS APIs.
• Preview images, audio and video:
A preview of image, audio and video files can be displayed before uploading with browsers supporting the required APIs.
• No browser plugins (e.g. Adobe Flash) required:
The implementation is based on open standards like HTML5 and JavaScript and requires no additional browser plugins.
• Graceful fallback for legacy browsers:
Uploads files via XMLHttpRequests if supported and uses iframes as fallback for legacy browsers.
• HTML file upload form fallback:
Allows progressive enhancement by using a standard HTML file upload form as widget element.
• Cross-site file uploads:
Supports uploading files to a different domain with cross-site XMLHttpRequests or iframe redirects.
• Multiple plugin instances:
Allows to use multiple plugin instances on the same webpage.
• Customizable and extensible:
Provides an API to set individual options and define callBack methods for various upload events.
• Multipart and file contents stream uploads:
Files can be uploaded as standard “multipart/form-data” or file contents stream (HTTP PUT file upload).
• Compatible with any server-side application platform:
Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads.

2. Basic Plugin Setup

2.1 HTML Setup

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>jQuery File Upload Example</title>
</head>
<body>
<input id="fileupload" type="file" name="files[]" data-url="server/php/" multiple>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/vendor/jquery.ui.widget.js"></script>
<script src="js/jquery.iframe-transport.js"></script>
<script src="js/jquery.fileupload.js"></script>
<script>
$(function () {
    $('#fileupload').fileupload({
        dataType: 'json',
        done: function (e, data) {
            $.each(data.result.files, function (index, file) {
                $('<p/>').text(file.name).appendTo(document.body);
            });
        }
    });
});
</script>
</body>
</html>

Response and data type

The example above sets the dataType option to json, expecting the server to return a JSON response for each uploaded file. However it’s also possible to handle HTML content types as response or any other dataType that you can handle in your done handler.

2.2 Display Upload Progress

The fileupload plugin triggers progress events for both individual uploads (progress) and all running uploads combined (progressall). Event handlers can be set via the event binding mechanism or as widget options.

$('#fileupload').fileupload({
    /* ... */
    progressall: function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $('#progress .bar').css(
            'width',
            progress + '%'
        );
    }
});

The previous code assumes a progress node with an inner element that displays the progress status via its width percentage:

<div id="progress">
    <div class="bar" style="width: 0%;"></div>
</div>

The inner element should have a different background color than the container node, set via CSS and needs a height applied:

.bar {
    height: 18px;
    background: green;
}

2.3 Tie a file to an element node during the life cycle of an upload

Often, you will display a file to upload in an element node. This can be done in the add callback.

To be able to refer to the same element node in other callbacks related to the upload, you can make use of the context option (which is actually an option of jquery.ajax):

$(function () {
    $('#fileupload').fileupload({
        dataType: 'json',
        add: function (e, data) {
            data.context = $('

').text('Uploading...').appendTo(document.body); data.submit(); }, done: function (e, data) { data.context.text('Upload finished.'); } }); });

2.4 Start Uploads with a button click

Based on the previous example, it’s possible to start uploads on the click of a button instead of automatically:

$(function () {
    $('#fileupload').fileupload({
        dataType: 'json',
        add: function (e, data) {
            data.context = $('

3. Requirements

3.1 Mandatory Requirements

• jQuery v. 1.6+
• jQuery UI widget factory v. 1.9+ (included)
• jQuery Iframe Transport plugin (included)

The jQuery UI widget factory is a requirement for the basic File Upload plugin, but very lightweight without any other dependencies from the jQuery UI suite. The jQuery Iframe Transport is required for browsers without XHR file upload support.

3.2 Optional Requirements

• JavaScript Templates engine v. 2.5.4+
• JavaScript Load Image library v. 1.13.0+
• JavaScript Canvas to Blob polyfill v. 2.1.1+
• blueimp Gallery v. 2.15.1+
• Bootstrap v. 3.2.0+
• Glyphicons

The JavaScript Templates engine is used to render the selected and uploaded files for the Basic Plus UI and jQuery UI.

The JavaScript Load Image library and JavaScript Canvas to Blob polyfill are required for the image previews and resizing functionality.

The blueimp Gallery is used to display the uploaded images in a lightbox.

The user interface of all versions except the jQuery UI version is built with Bootstrap and icons from Glyphicons.

4. Browsers

4.1 Desktop Browsers

The File Upload plugin is regularly tested with the latest browser versions and supports the following minimal versions:

• Google Chrome
• Apple Safari 4.0+
• Mozilla Firefox 3.0+
• Opera 11.0+
• Microsoft Internet Explorer 6.0+
• Microsoft Edge

4.2 Mobile Browsers

The File Upload plugin has been tested with and supports the following mobile browsers:

• Apple Safari on iOS 6.0+
• Google Chrome on iOS 6.0+
• Google Chrome on Android 4.0+
• Default Browser on Android 2.3+
• Opera Mobile 12.0+

5. Conclusion

To conclude, file upload with jQuery can be easily adapted to your websites using the plugin we presented and its’ features. You can find this plugin on GitHub following the link https://github.com/blueimp/jQuery-File-Upload. It also has detailed information on the plugin useage and a live demo. However, if you feel that you are searching for something else Kendo UI has another solution for file uploads that you can find here.

6. Download

Download
You can download the full source code of this example here: jQuery File Upload

Fabio Cimo

Fabio is a passionate student in web tehnologies including front-end (HTML/CSS) and web design. He likes exploring as much as possible about the world wide web and how it can be more productive for us all. Currently he studies Computer Engineering, at the same time he works as a freelancer on both web programming and graphic design.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
mike martin
4 years ago

Can you share a demonstration of this file upload in action? Thank you for sharing it.

Back to top button