Bootstrap File Input Demo bootstrap-fileinput

Thankful to Krajee!
to get more out of us.

NOTE: The plugins on this site, strive to use a lot of CSS3 and HTML5 features in addition to JQuery. Hence, one may find either CSS3, HTML5 or a mix of both to achieve a plugin's requirements in many implementations.

This plugin enhances the HTML 5 file input for Bootstrap 3.x into an advanced widget with file preview for various files, multiple selection, and more. This plugin is inspired by this blog article and Jasny's File Input plugin. The plugin enhances these concepts and simplifies the widget initialization with simple HTML markup on a file input. It offers support for previewing a wide variety of files i.e. images, text, html, video, audio, flash, and objects.

With release v4.0.0, the plugin now supports AJAX based uploads using HTML 5 FormData and XHR2 protocol, which is supported in most modern browsers. It also has inbuilt support for AJAX based file deletion from the server. This thereby allows powerful features to append, add, remove files on the fly. The plugin also has added DRAG & DROP support for ajax uploads. In the event, the browser does not support FormData or XHR2, the plugin degrades it to a normal form submission.

You need to setup the server methods to parse and return the right response via AJAX. You can setup uploads in two modes as described below.

This is the default mode, whereby the uploadAsync property is set to true. When uploading multiple files, the asynchronous mode allows triggering parallel server calls for each file upload. You can control the maximum number of files allowed at a time to be uploaded by setting the maxFileCount property. In asynchronous mode, progress of each thumbnail in the preview is validated and updated.


Receiving Data (on server)

Your server method as set in uploadUrl receives the following data from the plugin

  1. file data: This data is sent to the server in a format very similar to the form file input. For example in PHP you can read this data as $_FILES['input-name'], where input-name is the name attribute of your input. If you do not set a name attribute for your input, the name is defaulted to file_data. Note that multiple file uploads require that you set multiple property to true for your input. So in PHP you would receive the file data as $_FILES['file_data']

  2. extra data: The plugin can send additional data to your server method. This can be done by setting uploadExtraData as an associative array object in key value pairs. So if you have setup uploadExtraData={id:'kv-1'}, in PHP you can read this data as $_POST['id'].


Sending Data (from server)

Your server method as set in uploadUrl must send data back as a json encoded object. The only key you must send is the error which will be the error message for the upload and will help the plugin to identify error in the file upload. For example the response from server would be sent as {error: 'You are not allowed to upload such a file.'}. Note: The plugin will automatically validate and display ajax exception errors.

In this mode, the uploadAsync property is set to false. This will trigger just one batch upload call to the server and send files from client to server as an array object. Even in this mode, you can control the maximum number of files allowed at a time to be uploaded by setting the maxFileCount property. However, in synchronous mode, progress will be only at a overall level. Progress of each thumbnail in the preview is not exactly validated and updated. However, the plugin offers you a method of identifying upload errors faced for each file.


Receiving Data (on server)

Your server method as set in uploadUrl receives the following data from the plugin

  1. file data: This data is sent to the server in a format very similar to the form file input. For example in PHP you can read this data as $_FILES['input-name'], where input-name is the name attribute of your input. Also as in asynchronous mode before, if you do not set a name attribute for your input, the name is defaulted to file_data. You must set your input name as an array format as mentioned in this web tip, in addition to setting multiple property to true. If you do not set your input name as an array format, you would receive only the first file on your server. In PHP you would receive the file data as $_FILES['input-name'], which will be an array of file objects.

  2. extra data: The plugin can send additional data to your server method. This can be done by setting uploadExtraData as an associative array object in key value pairs. So if you have setup uploadExtraData={id:'kv-1'}, in PHP you can read this data as $_POST['id'].


Sending Data (from server)

In synchronous mode as well, the uploadUrl must send data back as a json encoded object. In this case you send two pieces of information.

  • error: string, which will be the error message for the entire batch upload and will help the plugin to identify error in the file upload.

  • errorkeys: array, the keys (zero-based indexes for the file data received) for the files that have errored out. Based on this data, the plugin will automatically set the thumbnails and each individual preview file to error out.

For example the response from server would be sent as {error: 'You have faced errors in 4 files.', errorKeys: [0, 3, 4, 5]}. Note: The plugin will automatically validate and display ajax exception errors.

Scenario 1

AJAX based uploads using drag and drop functionality. Just set the uploadUrl data property and multiple to true. Modify files before upload i.e. append or delete. You can read the uploaded files on your server for the input name kartik-input-700.



Scenario 2

Batch uploads in synchronous mode without parallel server calls (check uploadAsync property).



Scenario 3

AJAX based uploads with initial preview and initial preview delete URL. The overwriteInitial property is set to false.



// Scenario 1: AJAX based uploads using drag and drop functionality. Just set the `uploadUrl` data property and `multiple`
// to `true`. Modify files before upload i.e. append or delete. You can read the uploaded files on your server for the 
// input name `kartik-input-700`.
<input id="input-700" name="kartik-input-700" type="file" multiple=true class="file-loading" data-upload-url="/site/file-upload" data-max-file-count="10">

// Scenario 2: Batch upload in synchronous mode without parallel server calls (check `uploadAsync` property)
<input id="input-701" name="kartik-input-701" type="file" multiple=true class="file-loading" data-upload-url="/site/file-upload" data-upload-async="false" data-max-file-count="10">

// Scenario 3: AJAX based uploads with initial preview and initial preview delete URL. The `overwriteInitial` property is set to false.
<input id="input-702" name="kartik-input-702" type="file" multiple=true class="file-loading" data-upload-url="/site/file-upload" data-max-file-count="10">
<script>
$("#input-702").fileinput({
    uploadUrl: "' . Url::to(['/site/file-upload']) . '"
    maxFileCount: 10,
    overwriteInitial: false,
    initialPreview: [
        '<img src="/images/examples/Desert.jpg " class="file-preview-image">',
        '<img src="/images/examples/Jellyfish.jpg " class="file-preview-image">',
    ],
    initialPreviewConfig: [
        {caption: "Desert.jpg", width: "120px", url:"/site/file-delete", key:1},
        {caption: "Jellyfish.jpg", width: "120px", url:"/site/file-delete", key:2}
    ],
});
</script>

Automatically convert a file input to a bootstrap file input widget by setting its class as file

Hide file preview thumbnails

Use file input attributes (e.g. multiple upload) for setting input behavior and data attributes to control plugin options. For example, hide/show display of upload button and caption.

Set the file input widget to be readonly or disabled

Initialize file input widget via javascript. Hide the caption and display widget with only buttons. You can add the file-loading class to show a spinning indicator, while the plugin loads.

Change size of whole widget (e.g. bootstrap input group styling) and set max files count allowed to 10.
// Automatically convert a file input to a bootstrap file input widget
// by setting its class as 'file'
<input id="input-1" type="file" class="file">

// Hide file preview thumbnails
<input id="input-1a" type="file" class="file" data-show-preview="false">

// Use file input attributes (e.g. multiple upload) for setting input behavior and data attributes to 
// control plugin options. For example, hide/show display of upload button and caption.
<input id="input-2" type="file" class="file" multiple="true" data-show-upload="false" data-show-caption="true">

// Set the file input widget to be readonly or disabled
 <input id="input-3a" type="file" class="file" readonly="true">
 <input id="input-3b" type="file" class="file" disabled="true">

// Initialize file input widget via javascript. Hide the caption and display widget with only buttons.
<input id="input-4" type="file" multiple="true">
/* Javascript call to initialize plugin with your desired options */
$("#input-4").fileinput({showCaption: false}); 

// Change size of whole widget (e.g. bootstrap input group styling)  and set max files count 
// allowed to 10.
<input id="input-5" type="file" multiple="true">
/* Javascript call to initialize plugin with your desired options */
$("#input-5").fileinput({showUpload: false, maxFileCount: 10, mainClass: "input-group-lg"});

Set maximum file upload size to 100 KB. Display preview on load with preset files/images and captions with overwriteInitial set to false. So the initial preview is always displayed when additional files are overwritten (useful for multiple upload) scenario.

Display preview on load with preset files/images and captions with overwriteInitial set to true.

Display the widget as a single block button

Show only image files for selection & preview. Control button labels, styles, and icons for the browse, upload, and remove buttons.

Preview section control. Change preview background and allow text files ONLY for selection as well as preview.

Advanced customization using templates. For example, change position of buttons from right to left.


Using plugin methods to alter input at runtime. For example, click the Modify button to disable the plugin and change plugin options.

Allow only image and video file types to be uploaded. You can configure the condition for validating the file types using fileTypeSettings.

Allow only specific file extensions.

Disable preview and customize your own error container and messages.
// Set maximum file upload size to 100 KB. Display preview on load with preset files/images and captions
// with `overwriteInitial` set to false. So the initial preview is always displayed when additional files 
// are overwritten (useful for multiple upload) scenario.
<input id="input-24" type="file" multiple="true">
$("#input-24").fileinput({
    initialPreview: [
        "<img src='/images/moon.jpg' class='file-preview-image' alt='The Moon' title='The Moon'>",
        "<img src='/images/earth.jpg' class='file-preview-image' alt='The Earth' title='The Earth'>",
    ],
    overwriteInitial: false,
    maxFileSize: 100,
    initialCaption: "The Moon and the Earth"
});

// Display preview on load with preset files/images and captions
// with `overwriteInitial` set to true.
<input id="input-25" type="file" multiple="true">
$("#input-25").fileinput({
    initialPreview: [
        "<img src='/images/moon.jpg' class='file-preview-image' alt='The Moon' title='The Moon'>",
        "<img src='/images/earth.jpg' class='file-preview-image' alt='The Earth' title='The Earth'>",
    ],
    overwriteInitial: true,
    initialCaption: "The Moon and the Earth"
});

// Display the widget as a single block button
<input id="input-20" type="file">
/* Initialize your widget via javascript as follows */
$("#input-20").fileinput({
	browseClass: "btn btn-primary btn-block",
	showCaption: false,
	showRemove: false,
	showUpload: false
});

// Show only image files for selection & preview. Control button labels, styles, 
// and icons for the browse, upload, and remove buttons.
<input id="input-21" type="file" accept="image/*" >
<script>
/* Initialize your widget via javascript as follows */
$("#input-21").fileinput({
	previewFileType: "image",
	browseClass: "btn btn-success",
	browseLabel: "Pick Image",
	browseIcon: '<i class="glyphicon glyphicon-picture"></i>',
	removeClass: "btn btn-danger",
	removeLabel: "Delete",
	removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
	uploadClass: "btn btn-info",
	uploadLabel: "Upload",
	uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
});
</script>

// Preview section control. Change preview background and allow text files ONLY 
// for selection as well as preview.
<input id="input-22" type="file" class="file-loading" accept="text/plain" multiple=true>
<script>
$("#input-22").fileinput({
    previewFileType: "text",
    allowedFileExtensions: ["txt", "md", "ini", "text"],
    previewClass: "bg-warning"
});
</script>
 
// Advanced customization using templates. For example, change position of buttons 
// from right to left.
<input id="input-23" type="file" multiple="true">
<script>
$("#input-23").fileinput({
	showUpload: false,
	layoutTemplates: {
        main1: "{preview}\n" +
        "<div class=\'input-group {class}\'>\n" +
        "   <div class=\'input-group-btn\'>\n" +
        "       {browse}\n" +
        "       {upload}\n" +
        "       {remove}\n" +
        "   </div>\n" +
        "   {caption}\n" +
        "</div>"
    }
});
</script>

// Using plugin methods to alter input at runtime. For example, click the 
// Modify button to disable the plugin and change plugin options.
<input id="input-40" type="file" class="file" multiple=true>
<script>
$(".btn-modify").on("click", function() {
    $btn = $(this);
    if ($btn.text() == "Modify") {
        $("#input-40").fileinput("disable");
        $btn.html("Revert");
        alert("Hurray! I have disabled the input and hidden the upload button.");
    }
    else {
        $("#input-40").fileinput("enable");
        $btn.html("Modify");
        alert("Hurray! I have reverted back the input to enabled with the upload button.");
    }
});
</script>

// Allow only image and video file types to be uploaded. You can configure 
// the condition for validating the file types using `fileTypeSettings`.
<input id="input-41" type="file" multiple=true>
<script>
$("#input-41").fileinput({
    maxFilesNum: 10,
    allowedFileTypes: ["image", "video"]
});
</script>

// Allow only specific file extensions to be uploaded. 
<input id="input-42" type="file" multiple=true>
<script>
$("#input-42").fileinput({
    maxFilesNum: 10,
    allowedFileExtensions: ["jpg", "gif", "png", "txt"]
});
</script>

// Disable preview and customize your own error container and messages.
<input id="input-43" type="file" multiple=true>
<div id="errorBlock43" class="help-block"></div>
<script>
$("#input-43").fileinput({
    showPreview: false,
    allowedFileExtensions: ["zip", "rar", "gz", "tgz"],
    elErrorContainer: "#errorBlock43"
    // you can configure `msgErrorClass` and `msgInvalidFileExtension` as well
});
</script>