Krajee

Bootstrap File Input

Thankful to Krajee! BUY A COFFEEor to get more out of us.

An enhanced HTML 5 file input for Bootstrap 5.x or Bootstrap 4.x or Bootstrap 3.x with file preview for various files, offers multiple selection, and more. The plugin allows you a simple way to setup an advanced file picker/upload control built to work specially with Bootstrap CSS3 styles. It enhances the file input functionality further, by offering support to preview a wide variety of files i.e. images, text, html, video, audio, flash, and objects. In addition, it includes AJAX based uploads, dragging & dropping files, viewing upload progress, and selectively previewing, adding, or deleting files.

View a complete demo.

NEW: Release v5.0.0 is a major rewrite that incorporates various new enhancements and features like resumable chunk uploads and more. A summary of the features available with this release are documented in the Release 5.0.0 milestone.

Bootstrap 5.x Support is available with release v5.2.0. From release v5.2.0, the bootstrap version is also auto detected by the plugin based on the bootstrap JS library loaded. This can also be overridden via the new global property $.fn.fileinputBsVersion. Note that as of May 2021, an issue exists with Bootstrap 5.x on Modal dialog initialization which is recorded in this issue with a workaround.

Bootstrap 4.x Support is also available with release v4.4.4. The release 4.4.4 also includes various preview and styling enhancements including support for smaller screen devices.

Post release v4.0.0, the plugin 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.

This plugin was initially inspired by this blog article and Jasny's File Input plugin. But the plugin has now matured with various additional features and enhancements to be a complete (yet simple) file management tool and solution for web developers.

Note

You can refer this webtip for an example of processing ajax based uploads using PHP.

Tip

Not seeing the updated content on this page! Hard refresh your browser to clean cache for this page (e.g. SHIFT-F5 on Windows Chrome)

File Input Features

  • The plugin will convert a simple HTML file input to an advanced file picker control. Will help fallback to a normal HTML file input for browsers not supporting JQuery or Javascript.

  • The file input consists of the following three sections with options and templates to control the display:

    • file caption section: to display a brief information of the file(s) selected

    • file action buttons section: to browse, remove, and upload files.

    • file preview section: to display the selected files on client for preview (supports preview of image, text, flash, and video file types). Other file types will be displayed as normal thumbnails.

  • The plugin automatically converts an input with type = file to an advanced file picker input if you set its class = file. All options to the input can be passed as HTML5 data attributes.

  • Ability to select and preview multiple files. Uses HTML 5 File reader API to read and preview files. Displays the progress of files being being loaded onto the preview zone, in case many files are chosen.

  • Ability to copy and paste files or images from the clipboard on to the fileinput plugin (just focus on the file caption name input and paste your clipboard content).

  • Ability to drag and drop files or images on to the fileinput plugin.

  • Offers predefined templates and CSS classes which can be changed to style your file-input display as per your needs.

  • Ability to configure the plugin to show an initial preview of images/files with initial caption (more useful for record update scenarios). Refer the initialPreview, initialPreviewConfig, and initialCaption properties in the plugin options section for configuring this.

  • Ability to zoom content as a detailed preview. See a slideshow of zoomed content in preview, maximize to borderless or fullscreen preview.

  • Ability to sort/rearrange content in the initial preview via drag and drop.

  • Ability to theme the widget entirely and control styling and layouts.

  • Supports multi language widgets on same page through locales/translations.

  • Option to show/hide any or all of the following:

    • caption section

    • preview section

    • upload button

    • remove button

  • Customise the location of the target container elements to display the entire plugin, the caption container, the caption text, the preview container, preview image, and preview status.

  • For text file previews, autowrap the text to the thumbnail width, and show a wrap indicator link to display complete text on hover. You can customize the wrap indicator (which defaults to …).

  • Customise the messages for preview, progress, and files selected.

  • Upload action defaults to form submit. Supports an upload route/server action parameter for custom ajax based upload.

  • Triggers JQuery events for advanced development. Events currently available are filereset, fileclear, filecleared, fileloaded, and fileerror.

  • Disabled and readonly file input support.

  • Dynamically auto size the file captions for long file names exceeding container width.

  • Raise new fileimageuploaded event that fires after image is completely loaded on the preview container.

  • Autosize preview images when they exceed the size of the preview container.

  • Completely templatized and extensible to allow configuration of the file-input the way the developer wants.

  • Preview intelligence based on various file preview types. The inbuilt file support types are categorized as image, text, html, video, audio, flash, object, and other.

  • allowedPreviewTypes: You can now configure which all file types are allowed to be shown as a preview. This defaults to ['image', 'html', 'text', 'video', 'audio', 'flash', 'object']. Thus all file types are treated as an object to preview by default. For exampleTo preview only image and video, you can set this to ['image', 'video']. To disable content preview for all file-types and show the previewIcon instead as a thumbnail, set this to null, empty, or false.

  • allowedPreviewMimeTypes: In addition to allowedPreviewTypes, you can also control which all mime types can be displayed for preview. This defaults to null, meaning all mime types are supported. >NOTE: With release 2.5.0 you can now control which file types or extensions are allowed for upload by setting allowedFileTypes and allowedFileExtensions.

  • layoutTemplates: Allows you to configure all layout template settings within one property. The layout objects that can be configured are: main1, main2, preview, caption, and modal.

  • previewTemplates: All preview templates for each preview type have been combined into one property, instead of separate templates for image, text etc. The keys are the formats as set in allowedPreviewTypes and values are the templates used for previewing. There are default prebuilt templates for each preview file type (generic, image, text, html, video, audio, flash, object, and other). The generic template is used only for displaying initialPreview content using direct markup.

  • previewSettings: Allows you to configure width and height for each preview image type. The plugin has default widths and heights predefined for each type i.e image, text, html, video, audio, flash, and object.

  • fileTypeSettings: Allows you to configure and identify each preview file type using a callback. The plugin has default callbacks predefined to identify each type i.e image, text, html, video, audio, flash, and object.

  • Replacing tags within templates has been enhanced. With this release it will automatically check for multiple occurrences of each tag to replace within a template string.

  • Manipulate events and add your own custom validation messages easily by returning output to abort uploads in any of the other events.

  • Support for translations and locales.

Note

Flash preview will require Shockwave flash to be installed and supported by the client browser. The flash preview currently works successfully with webkit browsers only. Video & Audio formats are however supported by all modern browsers that support the HTML5 video/audio tags. Note that browsers have limited number of video/audio formats supported by the HTML5 video element (e.g. mp4, webm, ogg, mp3, wav). The size of video files are recommended to be small (to be controlled through maxFileSize property) so that it does not affect the preview performance. You can copy a few files from the examples directory of this plugin repo, to test a few examples of flash and video files.

File Upload Features

With release 4.0.0, the plugin now also includes inbuilt support for AJAX Uploads and selectively adding or deleting files. AJAX upload functionality are built upon HTML5 FormData and XMLHttpRequest Level 2 standards. Most modern browsers do support this standard, but the plugin will automatically degrade to normal form based submission for unsupported browsers.

  • Add functionality for AJAX based UPLOAD using HTML5 FormData (most modern browsers support it). Will degrade to normal Form Based File submission if this is not supported.

  • To use AJAX Upload, one must set the uploadUrl property.

  • Enhance plugin to now allow files to be added, appended, removed (based on FEEDBACK from many). Thus one can append files to preview.

  • New DRAG & DROP zone available in preview to drag and drop files and append.

  • Delete or upload files one by one OR in batch.

  • If showPreview is set to false, or uploadUrl is not supported plugin will degrade to normal form based upload.

  • Configurable indicators for file awaiting upload, file successfully uploaded, files errored in upload.

  • Ability to add extra form data with ajax based uploads.

  • Upload progress bar and individual thumbnail upload indicators.

  • Ability to cancel and abort ongoing AJAX uploads.

  • Build up initial preview content (e.g. gallery of saved images). You can set initial preview actions (prebuilt support for initial preview delete). Other custom action buttons can be set for initial preview thumbnails as well.

  • Ensure plugin is still lean in size and optimized for performance inspite of the above features by optimally utilizing HTML5 & jquery features only.

  • Automatically refresh preview with content from server as soon as an ajax upload finishes.

The bootstrap-fileinput plugin can be installed automatically or manually using one of these options:

Bower Package Manager


Installation via bower package manager is as simple as running:

$ bower install bootstrap-fileinput

Node Package Manager


Installation via NPM is as simple as running:

$ npm install bootstrap-fileinput

Composer Package Manager


You can install bootstrap-fileinput via composer package manager. Either run:

$ php composer.phar require kartik-v/bootstrap-fileinput "dev-master"

or add:

"kartik-v/bootstrap-fileinput": "dev-master"

to your composer.json file

Manual Install


You can also manually install the plugin easily to your project. Just download the source ZIP or TAR ball and extract the plugin asset files and folders into your project.

Note

The plugin will automatically convert fields of [input type="file"] to a file input control, if you attach a css class file to the input. But, if you are initializing the plugin separately via javascript, then DO NOT ATTACH the css class file to the input (as it will result in duplicate initializations and the javascript code maybe skipped).

Load the following assets in your header.

<!-- bootstrap 5.x or 4.x is supported. You can also use the bootstrap css 3.3.x versions -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" crossorigin="anonymous">

<!-- default icons used in the plugin are from Bootstrap 5.x icon library (which can be enabled by loading CSS below) -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.min.css" crossorigin="anonymous">

<!-- alternatively you can use the font awesome icon library if using with `fas` theme (or Bootstrap 4.x) by uncommenting below. -->
<!-- link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.3/css/all.css" crossorigin="anonymous" -->

<!-- the fileinput plugin styling CSS file -->
<link href="https://cdn.jsdelivr.net/gh/kartik-v/bootstrap-fileinput@5.5.0/css/fileinput.min.css" media="all" rel="stylesheet" type="text/css" />

<!-- if using RTL (Right-To-Left) orientation, load the RTL CSS file after fileinput.css by uncommenting below -->
<!-- link href="https://cdn.jsdelivr.net/gh/kartik-v/bootstrap-fileinput@5.5.0/css/fileinput-rtl.min.css" media="all" rel="stylesheet" type="text/css" /-->

<!-- the jQuery Library -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>

<!-- buffer.min.js and filetype.min.js are necessary in the order listed for advanced mime type parsing and more correct
     preview. This is a feature available since v5.5.0 and is needed if you want to ensure file mime type is parsed 
     correctly even if the local file's extension is named incorrectly. This will ensure more correct preview of the
     selected file (note: this will involve a small processing overhead in scanning of file contents locally). If you 
     do not load these scripts then the mime type parsing will largely be derived using the extension in the filename
     and some basic file content parsing signatures. -->
<script src="https://cdn.jsdelivr.net/gh/kartik-v/bootstrap-fileinput@5.5.0/js/plugins/buffer.min.js" type="text/javascript"></script>
<script src="https://cdn.jsdelivr.net/gh/kartik-v/bootstrap-fileinput@5.5.0/js/plugins/filetype.min.js" type="text/javascript"></script>

<!-- piexif.min.js is needed for auto orienting image files OR when restoring exif data in resized images and when you
    wish to resize images before upload. This must be loaded before fileinput.min.js -->
<script src="https://cdn.jsdelivr.net/gh/kartik-v/bootstrap-fileinput@5.5.0/js/plugins/piexif.min.js" type="text/javascript"></script>

<!-- sortable.min.js is only needed if you wish to sort / rearrange files in initial preview. 
    This must be loaded before fileinput.min.js -->
<script src="https://cdn.jsdelivr.net/gh/kartik-v/bootstrap-fileinput@5.5.0/js/plugins/sortable.min.js" type="text/javascript"></script>

<!-- bootstrap.bundle.min.js below is needed if you wish to zoom and preview file content in a detail modal
    dialog. bootstrap 5.x or 4.x is supported. You can also use the bootstrap js 3.3.x versions. -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>

<!-- the main fileinput plugin script JS file -->
<script src="https://cdn.jsdelivr.net/gh/kartik-v/bootstrap-fileinput@5.5.0/js/fileinput.min.js"></script>

<!-- following theme script is needed to use the Font Awesome 5.x theme (`fa5`). Uncomment if needed. -->
<!-- script src="https://cdn.jsdelivr.net/gh/kartik-v/bootstrap-fileinput@5.5.0/themes/fa5/theme.min.js"></script -->

<!-- optionally if you need translation for your language then include the locale file as mentioned below (replace LANG.js with your language locale) -->
<script src="https://cdn.jsdelivr.net/gh/kartik-v/bootstrap-fileinput@5.5.0/js/locales/LANG.js"></script>

If you noticed, you need to load the jquery.min.js and bootstrap.min.css in addition to the fileinput.min.css and fileinput.min.js. For enabling the default icons used in the plugin load the Bootstrap 5.x icon library bootstrap.min.css. Alternatively, the Font Awesome theme can be enabled by loading FontAwesome Icons CSS file and its theme file fa5/theme.min.js. The locale file for your language LANG.js can be optionally included for translating for your language if needed. In case you need RTL (Right-To-Left) orientation, then you need to load the fileinput-rtl.min.css stylesheet file after fileinput.min.css

Optional Dependent Plugins

  • The piexif.min.js file is the source for the Piexifjs plugin by hMatoba. It is required to be loaded before fileinput.min.js when you wish to auto orient JPEG image files based on their orientation tag. This library is also needed for restoring the exif data to the image files when using the image resize feature of the bootstrap-fileinput plugin.

  • The sortable.min.js file is the source for the Sortable plugin by rubaxa. It is required to be loaded before fileinput.min.js if you wish to sort the thumbnails in the initial preview.

Initialize the plugin on your page. For example to initialize using javascript - the following code can be placed in document.ready or at any place you wish on your page.

// Optional setup: bootstrap library version will be auto-detected based on the 
// loaded bootstrap JS library bootstrap.min.js. But if you wish to override the 
// bootstrap version yourself, then you can set the following property before
// the plugin init script (available since plugin release v5.5.0)

$.fn.fileinputBsVersion = "3.3.7"; // if not set, this will be auto-derived

// initialize plugin with defaults
$("#input-id").fileinput();
 
// with plugin options
$("#input-id").fileinput({'showUpload':false, 'previewFileType':'any'});

The #input-id is the identifier for the input (e.g. type=file) on your page, which is hidden automatically by the plugin.

Alternatively, you can directly set the plugin options to any input, through HTML 5 data attributes to your input field. Note that for this case, you need to attach the CSS class file to the input.

As noted earlier, when initializing plugin via javascript (step 2a), you MUST NOT attach the CSS class file to the input.

<input id="input-id" type="file" class="file" data-preview-file-type="text">
  • Bootstrap 5.x or Bootstrap 4.x or Bootstrap 3.x. However, the plugin can be customized for any CSS framework using templates. Bootstrap 5.x framework is supported since release v5.5.0. Bootstrap 4.x framework is supported since release v4.4.4.

  • Latest JQuery

  • Most modern browsers supporting HTML5 file inputs and FileReader API including CSS3 & JQuery. For details, refer the browser support section.

  • For file previews to work, the browser must support the HTML5 FileReaderAPI - else the plugin will auto-degrade to a normal file input. For Internet Explorer, one must use IE versions 10 and above. IE9 and below will work as a normal file input, and will not support multiple file selection or the HTML 5 FileReader API.

  • With release 4.0, AJAX uploads are supported. AJAX uploads require that the browser support HTML5 FormData and XHR2 (XMLHttpRequest 2). Most modern browsers support FormData and XHR2. The plugin will automatically degrade to normal form based submission for browsers not supporting AJAX uploads.

The plugin uses HTML 5 features to achieve various functionalities. Most modern browsers support these features. However, to know if your browser supports these functions you must run through these checks once below.

Functionality Description Support
File Input Multiple Allow users to select multiple files using the native HTML file input. Browsers
Input File Directory Uses the webkitdirectory attribute on the <input type="file"> element. This allows entire directory with file contents (and any subdirectories) to be selected. Browsers
HTML 5 File API Allow reading and previewing files on the preview pane using the plugin Browsers
HTML 5 Blob Allow managing/constructing file blobs for enabling the resumable upload functionality for the plugin. Browsers
HTML 5 Blob Slice Allow slicing file blobs for enabling the file chunks upload functionality for the plugin. Browsers
HTML 5 XHR2 & FormData Allow using ajax uploads with ability to append / delete files and track using a progress bar. Browsers
HTML5 Drag Drop The plugin uses HTML 5 drag and drop ability to drag and drop files from your PC/device into the file input dropzone. This is supported both for form based and ajax based uploads. However for form based uploads it is restricted to browsers like Chrome and Mozilla that support assigning FileList object to the native file input. Browsers
HTML5 Canvas HTML 5 Canvas offers a method of generating fast, dynamic graphics using JavaScript. The plugin uses HTML5 canvas for managing image files via JavaScript. This is required if you wish to resize image files before upload. Browsers
HTML5 Download Attribute The download attribute on an hyperlink specifies that the target will be downloaded when a user clicks on the hyperlink. The value of the attribute will be the name of the downloaded file. Required if you wish to use the download action button for each thumbnail in a more easy and effective manner. Browsers

Largely speaking, the plugin can be configured in one of the following two different modes for upload. IMPORTANT: Do not try to combine the modes below to receive file data as you will receive inconsistent and/or erroneous output.

Mode 1: Form Submission


In this mode, you do not set the uploadUrl property. The plugin will use the native file input to store files and it can be read after a normal FORM submission (you must envelop the input within a FORM). This is useful for single file uploads OR simpler scenarios of multiple file uploads. Configuration is straightforward as you can read all data POSTED from a native form submission. However, note that the native file input is read only and cannot be modified or updated by external code. Especially for multiple file input selections, ONE cannot append files to an already selected file list. If one tries to select files on an already selected file input, it will overwrite and clear the previous selection. Similarly, one cannot selectively remove/delete files that have been added before upload in this mode.

Note

Drag and dropping of files is supported for form based uploads since release v4.4.8. However for form based uploads it is restricted to browsers like Chrome and Mozilla that support assigning FileList object to the native file input.

Mode 2: Ajax Submission


In this mode, you MUST SET the uploadUrl property to a VALID ajax processing server action/URL. If the uploadUrl is set, then the plugin automatically assumes an ajax upload for the scenario. The plugin offers advanced features for ajax submission that is not available in form submission. Features like appending/removing files in preview zone, getting a progress bar for your uploads, image resizing etc. are all possible ONLY IN THIS mode. Your browser must support HTML5 FormData/XHR2 for this to work and your server code that processes the ajax call must return a valid JSON response.

Note

As an advanced scenario, the plugin allows you to process the ajax upload even if there are no files selected but a valid uploadExtraData is sent with the ajax response. The events filebatchpreupload, filebatchuploadsuccess, filebatchuploadcomplete, or filebatchuploaderror will be triggered in this case. It will not have any data for the files selected, but will allow the extra data to be sent.

Modes Compared


Functionality / Requirement Form Submission Ajax Submission
Support single & multiple file upload
Preview files using HTML 5 FileAPI
Read files directly via form submission
Individual file delete icon for each preview thumbnail 1 2
Individual file upload icon for each preview thumbnail
Requires valid JSON response back from server
Requires browser support for HTML5 FormData/XHR2
Server code to process ajax and send JSON Response
Drag & Drop Files using drop zone 3
Ability to append files to already selected list
Ability to delete files to already selected list 1
Progress bar for uploads
Upload stats for uploads
Resumable / Chunk uploads
Read additional form data Directly via form submit
Via uploadExtraData
Resize image files before upload
  • 1 - Via initialPreviewConfig (not applicable for client selected files that are yet to be uploaded).

  • 2 - For both server uploaded files (via initialPreviewConfig) and client selected files at runtime.

  • 3 - Drag & drop for form based uploads is supported since release v4.4.8. However for form based uploads it is restricted to browsers like Chrome and Mozilla that support assigning FileList object to the native file input.

As shown in the usage section, translations are now enabled with release 4.1.8. Follow these steps to enable translations for your language:

  • Load your language locale script file on your page from /js/locales/<lang>.js. This script must be loaded after the core fileinput.js file, where <lang> is the language code (e.g. de, fr etc.). If your locale file does not exist, you can create the translations for the new language by submitting a github pull request to add to this folder. Check the sample locale file to copy and create a translation configuration for your own language.

  • Configure the plugin's language property to the same language code identified by <lang> above.

You need to setup the server methods to parse and return the right response via AJAX. You can setup uploads in asynchronous OR synchronous 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

  • file data: The file data is sent to the server in a format very similar to how you would receive data via a native HTML file input (via form submission). For example in PHP you can read this data as $_FILES['input-name'], where input-name is the name attribute of your file 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']

  • 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'].

    Note

    In asynchronous mode, you will ALWAYS receive a single FILE on your server action that processes the ajax upload. Basically the plugin will trigger parallel ajax calls for every file selected for upload. You need to write your server upload logic accordingly so that you always read and upload ONE file. Similarly, in the sending data section below, you must return an initialPreview that reflects data only for the single file received.

Sending Data (from server)

Your server method as set in uploadUrl must send data back as a json encoded object. For example, the server could return a JSON object like below:

// example JSON response from server
{
    error: 'An error exception message if applicable',
    initialPreview: [
        // initial preview thumbnails for server uploaded files if you want it displayed immediately after upload
    ],
    initialPreviewConfig: [
        // configuration for each item in initial preview 
    ],
    initialPreviewThumbTags: [
        // initial preview thumbnail tags configuration that will be replaced dynamically while rendering
    ],
    append: true // whether to append content to the initial preview (or set false to overwrite)
}

If you have NO DATA to be sent from the server then you MUST at least return an empty JSON object e.g. {}. The JSON object that you return from the server consists of 5 pieces of information. Note that in asynchronous mode, you will ALWAYS receive ONE FILE record from the server - so adjust your code accordingly.

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

  • initialPreview: array, the list of image files or any HTML markup to point to your uploaded files. You will always send ONE row in this array - because you will always receive ONE file with the upload in asynchronous mode. If this property is set, the plugin will automatically replace the files dynamically in the preview content after upload success. The configuration for this is similar to the initialPreview option setting. For example:

    initialPreview: [
        '<img src='/images/desert.jpg' class='file-preview-image' alt='Desert' title='Desert'>'
    ]
    
  • initialPreviewConfig: array, the configuration to identify properties for each file markup in initialPreview item (that is setup as part of initialPreview). You will always send ONE row in this array - because you will always receive ONE file with the upload in asynchronous mode. If this property is set, the plugin will automatically replace the files dynamically in the preview content after upload success. The configuration for this is similar to the initialPreviewConfig option setting. For example:

    initialPreviewConfig: [
        {
            caption: 'desert.jpg', 
            width: '120px', 
            url: 'http://localhost/avatar/delete', // server delete action 
            key: 100, 
            extra: {id: 100}
        }
    ]
    
  • initialPreviewThumbTags: array, an array of objects corresponding to replacing tags within each initial preview thumbnail. The initial preview thumbnails set via initialPreview will read this configuration for replacing tags.

    // change thumbnail footer template
    // set initial preview template tags
    initialPreviewThumbTags:[
        {
            '{CUSTOM_TAG_NEW}': ' ',
            '{CUSTOM_TAG_INIT}': '<span class=\'custom-css\'>CUSTOM MARKUP</span>'
        }
    ]
    
  • append: boolean, whether to append the content to the initialPreview if you already set an initialPreview on INIT. If not set this defaults to true. If set to false, the plugin will overwrite the initialPreview content.

IMPORTANT

  • You MUST send a valid JSON response from your server, else the upload process will fail. Even if you do not encounter any error, you must at least send an empty JSON object {} from your server.

  • To trap and display a validation error, your JSON response data must include the error key, whose value will be the error HTML markup to display. This is to be setup as mentioned above.

  • You can also send in additional keys or data with your JSON response, for you to process them for advanced cases using events like fileuploaded.

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 displaying upload errors encountered for each file.

Receiving Data (on server)

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

  • file data: The file data is sent to the server in a format very similar to how you would receive data via a native HTML file input (via form submission). For example in PHP you can read this data as $_FILES['input-name'], where input-name is the name attribute of your file 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.

  • 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)

YIn synchronous mode as well, the uploadUrl must send data back as a json encoded object. For example the server could return a JSON object like below:

// example JSON response from server
{
    error: 'An error exception message if applicable',
    errorkeys: [], // array of thumbnail keys/identifiers that have errored out (set via key property in initialPreviewConfig
    initialPreview: [
    ], // initial preview configuration 
    initialPreviewConfig: [
        // initial preview configuration if you directly want initial preview to be displayed with server upload data
    ],
    initialPreviewThumbTags: [
        // initial preview thumbnail tags configuration that will be replaced dynamically while rendering
    ],
    append: true // whether to append content to the initial preview (or set false to overwrite)
}

If you have NO DATA to be sent from the server then you MUST at least return an empty JSON object e.g. {}. The JSON object that you return from the server needs to send these 6 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.

  • initialPreview: array, the list of image files or any HTML markup to point to your uploaded files. If this property is set, the plugin will automatically replace the files dynamically in the preview content after upload success. The configuration for this is similar to the initialPreview option setting. For example:

    initialPreview: [
        '<img src='/images/desert.jpg' class='file-preview-image' alt='Desert' title='Desert'>',
        '<img src='/images/jellyfish.jpg' class='file-preview-image' alt='Jelly Fish' title='Jelly Fish'>'
    ]
    
  • initialPreviewConfig: array, the configuration to identify properties for each file markup in initialPreview item (that is setup as part of initialPreview). If this property is set, the plugin will automatically replace the files dynamically in the preview content after upload success. The configuration for this is similar to the initialPreviewConfig option setting. For example:

    initialPreviewConfig: [
        {
            caption: 'desert.jpg', 
            width: '120px', 
            url: 'http://localhost/avatar/delete', // server delete action 
            key: 100, 
            extra: {id: 100}
        },
        {
            caption: 'jellyfish.jpg', 
            width: '120px', 
            url: 'http://localhost/avatar/delete', // server delete action 
            key: 101, 
            extra: function() { 
                return {id: $('#id').val()};
            },
        }
    ]
    
  • initialPreviewThumbTags: array, an array of objects corresponding to replacing tags within each initial preview thumbnail. The initial preview thumbnails set via initialPreview will read this configuration for replacing tags.

    // change thumbnail footer template
    // set initial preview template tags
    initialPreviewThumbTags:[
        {
            '{CUSTOM_TAG_NEW}': ' ',
            '{CUSTOM_TAG_INIT}': '<span class=\'custom-css\'>CUSTOM MARKUP 1</span>'
        },
        {
            '{CUSTOM_TAG_NEW}': ' ',
            '{CUSTOM_TAG_INIT}': '<span class=\'custom-css\'>CUSTOM MARKUP 2</span>'
        }
    ]
    
  • append: boolean, whether to append the content to the initialPreview if you already set an initialPreview on INIT. If not set this defaults to true. If set to false, the plugin will overwrite the initialPreview content.

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.

IMPORTANT

  • You MUST send a valid JSON response from your server, else the upload process will fail. Even if you do not encounter any error, you must at least send an empty JSON object {} from your server.

  • To trap and display a validation error, your JSON response data must include the error key, whose value will be the error HTML markup to display. In addition, you must typically also send the errorkeys for synchronous mode to identify the keys for files which faced errors. This is to be setup as mentioned above.

  • You can also send in additional keys or data with your JSON response, for you to process them for advanced cases using events like filebatchuploadsuccess.

With release v5.0, the plugin supports resumable and chunk uploads. This is a special ajax upload mode that can be activated by setting the enableResumableUpload property to true along with a valid uploadUrl. When resumable uploads are enabled - the plugin sends files by splitting it into chunks as determined by the properties within resumableUploadOptions. This upload mode is a special variant with additional capabilites than the synchronous and asynchronous uploads. Note that the files selected are sent in a sequence ONE at a time to uploadUrl. You can configure additional data to be sent for upload via uploadExtraData. This typically is useful to send an upload token for security authorizations.

Refer the resumable uploads demos for understanding few scenarios of setting up resumable and chunk uploads using the bootstrap-fileinput plugin.

NOTE

For resumable uploads (when enableResumableUpload property to true), the thumbnail specific upload button will not be displayed. The uploads will be controlled at the overall batch level, by the internal resumable manager, which allows pausing, resuming, and breaking files into necessary chunks. One therefore cannot upload a specific file thumbnail in this mode, when enableResumableUpload property to true. The plugin will automatically upload the batch of files in a serial sequence in this mode (resuming paused / broken uploads where required).

Receiving Data (on server)

Your server method as set in uploadUrl receives the following parameters as data from the plugin for resumable uploads. The plugin by default sends this information as a JSON object via POST. You can configure these parameter names via uploadParamNames.

  • fileId: string, unique file identifier for the file being uploaded generated via generateFileId

  • fileBlob: Blob, the actual file blob chunk sliced as per the chunk size (for example in PHP you would receive this as $_FILES['fileBlob']).

  • fileName: string, name of the file being uploaded

  • fileSize: double, size of the file being uploaded in bytes

  • fileRelativePath: string, client relative path of the file being uploaded

  • chunkIndex: string, index number of the current chunk

  • chunkSize: double, size of each file chunk being uploaded

  • chunkSizeStart: double, chunk start size for this current blob

  • chunkCount: integer, total number of file chunks being uploaded

  • retryCount: integer, total number of upload retries done so far for this chunk

In addition all the data which you set via uploadExtraData as key value pairs is also received by the server as part of the JSON response. This typically is useful to parse an upload token for security authorizations to detect the right upload user with right accesses .

Sending Data (from server)

Your server method as set in uploadUrl must return back the following response (in JSON FORMAT) to the plugin for resumable uploads. Not unlike async uploads you cannot just send an empty object. Send back the chunkIndex to identify success and/or the error to identify an error.

  • chunkIndex: string, index number of the processed chunk (typically you must return back the same chunkIndex you received via POST).

  • error: string, which will be the error message for the specific file being uploaded 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.

  • initialPreview: array, the list of image files or any HTML markup to point to your uploaded files. You will always send ONE row in this array - because you will always receive ONE file with the upload in asynchronous mode. If this property is set, the plugin will automatically replace the files dynamically in the preview content after upload success. The configuration for this is similar to the initialPreview option setting. Assuming you have set initialPreviewAsData to true, you can send the following for example:

    initialPreview: ['http://localhost/uploads/images/desert.jpg']
    
  • initialPreviewConfig: array, the configuration to identify properties for each file markup in initialPreview item (that is setup as part of initialPreview). You will always send ONE row in this array - because you will always receive ONE file with the upload in asynchronous mode. If this property is set, the plugin will automatically replace the files dynamically in the preview content after upload success. The configuration for this is similar to the initialPreviewConfig option setting. For example:

    initialPreviewConfig: [
        {
            caption: 'desert.jpg', 
            width: '120px', 
            url: 'http://localhost/avatar/delete', // server delete action 
            key: 100, 
            extra: {id: 100}
        }
    ]
    
  • initialPreviewThumbTags: array, an array of objects corresponding to replacing tags within each initial preview thumbnail. The initial preview thumbnails set via initialPreview will read this configuration for replacing tags.

    // change thumbnail footer template
    // set initial preview template tags
    initialPreviewThumbTags:[
        {
            '{CUSTOM_TAG_NEW}': ' ',
            '{CUSTOM_TAG_INIT}': '<span class=\'custom-css\'>CUSTOM MARKUP</span>'
        }
    ]
    
  • append: boolean, whether to append the content to the initialPreview if you already set an initialPreview on INIT. If not set this defaults to true. If set to false, the plugin will overwrite the initialPreview content.

Client Code Example (HTML / JS)

<input type="file" id="input-100" name="input-100[]" accept="image/*" multiple>
<script>
$('document').on('ready', function() {
    $("#input-id").fileinput({
        uploadUrl: "http://localhost/file-upload.php",
        enableResumableUpload: true,
        resumableUploadOptions: {
           // uncomment below if you wish to test the file for previous partial uploaded chunks
           // to the server and resume uploads from that point afterwards
           // testUrl: "http://localhost/test-upload.php"
        },
        uploadExtraData: {
            'uploadToken': 'SOME-TOKEN', // for access control / security 
        },
        maxFileCount: 5,
        allowedFileTypes: ['image'],    // allow only images
        showCancel: true,
        initialPreviewAsData: true,
        overwriteInitial: false,
        // initialPreview: [],          // if you have previously uploaded preview files
        // initialPreviewConfig: [],    // if you have previously uploaded preview files
        theme: 'fa5',
        deleteUrl: "http://localhost/file-delete.php"
    }).on('fileuploaded', function(event, previewId, index, fileId) {
        console.log('File Uploaded', 'ID: ' + fileId + ', Thumb ID: ' + previewId);
    }).on('fileuploaderror', function(event, data, msg) {
        console.log('File Upload Error', 'ID: ' + data.fileId + ', Thumb ID: ' + data.previewId);
    }).on('filebatchuploadcomplete', function(event, preview, config, tags, extraData) {
        console.log('File Batch Uploaded', preview, config, tags, extraData);
    });
});
</script>

Server Code Example (PHP)

// example of a PHP server code that is called in `uploadUrl` above
// file-upload.php script
header('Content-Type: application/json'); // set json response headers
$outData = upload(); // a function to upload the bootstrap-fileinput files
echo json_encode($outData); // return json data
exit(); // terminate

// main upload function used above
// upload the bootstrap-fileinput files
// returns associative array
function upload() {
    $preview = $config = $errors = [];}
    $targetDir = '/webroot/uploads';
    if (!file_exists($targetDir)) {
        @mkdir($targetDir);
    }
    $fileBlob = 'fileBlob';                      // the parameter name that stores the file blob
    if (isset($_FILES[$fileBlob]) && isset($_POST['uploadToken'])) {
        $token = $_POST['uploadToken'];          // gets the upload token
        if (!validateToken($token)) {            // your access validation routine (not included)
            return [
                'error' => 'Access not allowed'  // return access control error
            ];
        }
        $file = $_FILES[$fileBlob]['tmp_name'];  // the path for the uploaded file chunk 
        $fileName = $_POST['fileName'];          // you receive the file name as a separate post data
        $fileSize = $_POST['fileSize'];          // you receive the file size as a separate post data
        $fileId = $_POST['fileId'];              // you receive the file identifier as a separate post data
        $index =  $_POST['chunkIndex'];          // the current file chunk index
        $totalChunks = $_POST['chunkCount'];     // the total number of chunks for this file
        $targetFile = $targetDir.'/'.$fileName;  // your target file path
        if ($totalChunks > 1) {                  // create chunk files only if chunks are greater than 1
            $targetFile .= '_' . str_pad($index, 4, '0', STR_PAD_LEFT); 
        } 
        $thumbnail = 'unknown.jpg';
        if(move_uploaded_file($file, $targetFile)) {
            // get list of all chunks uploaded so far to server
            $chunks = glob("{$targetDir}/{$fileName}_*"); 
            // check uploaded chunks so far (do not combine files if only one chunk received)
            $allChunksUploaded = $totalChunks > 1 && count($chunks) == $totalChunks;
            if ($allChunksUploaded) {           // all chunks were uploaded
                $outFile = $targetDir.'/'.$fileName;
                // combines all file chunks to one file
                combineChunks($chunks, $outFile);
            } 
            // if you wish to generate a thumbnail image for the file
            $targetUrl = getThumbnailUrl($path, $fileName);
            // separate link for the full blown image file
            $zoomUrl = 'http://localhost/uploads/' . $fileName;
            return [
                'chunkIndex' => $index,         // the chunk index processed
                'initialPreview' => $targetUrl, // the thumbnail preview data (e.g. image)
                'initialPreviewConfig' => [
                    [
                        'type' => 'image',      // check previewTypes (set it to 'other' if you want no content preview)
                        'caption' => $fileName, // caption
                        'key' => $fileId,       // keys for deleting/reorganizing preview
                        'fileId' => $fileId,    // file identifier
                        'size' => $fileSize,    // file size
                        'zoomData' => $zoomUrl, // separate larger zoom data
                    ]
                ],
                'append' => true
            ];
        } else {
            return [
                'error' => 'Error uploading chunk ' . $_POST['chunkIndex']
            ];
        }
    }
    return [
        'error' => 'No file found'
    ];
}

// combine all chunks
// no exception handling included here - you may wish to incorporate that
function combineChunks($chunks, $targetFile) {
    // open target file handle
    $handle = fopen($targetFile, 'a+');
    
    foreach ($chunks as $file) {
        fwrite($handle, file_get_contents($file));
    }
    
    // you may need to do some checks to see if file 
    // is matching the original (e.g. by comparing file size)
    
    // after all are done delete the chunks
    foreach ($chunks as $file) {
        @unlink($file);
    }
    
    // close the file handle
    fclose($handle);
}

// generate and fetch thumbnail for the file
function getThumbnailUrl($path, $fileName) {
    // assuming this is an image file or video file
    // generate a compressed smaller version of the file
    // here and return the status
    $sourceFile = $path . '/' . $fileName;
    $targetFile = $path . '/thumbs/' . $fileName;
    //
    // generateThumbnail: method to generate thumbnail (not included)
    // using $sourceFile and $targetFile
    //
    if (generateThumbnail($sourceFile, $targetFile) === true) { 
        return 'http://localhost/uploads/thumbs/' . $fileName;
    } else {
        return 'http://localhost/uploads/' . $fileName; // return the original file
    }
}

Most of the plugin options can be retrieved at runtime by the following method.

var plugin = $('#file-input).data('fileinput');
console.log(plugin.initialPreview); // get initialPreview

The plugin supports the options as described in the link below.

View Plugin Options

The plugin has been implemented as extensions in the following frameworks

Sl. Framework Extension Source Developed By Extension Demo
1. Yii Framework 2.0 Yii2 Widgets Krajee Yii2 File Input

Do you know any other framework extension using this plugin which is not listed here? Tell us so that we can consider its inclusion in this list.

bootstrap-fileinput is released under the BSD 3-Clause License. See the bundled LICENSE.md for details.

Note

You can now visit the Krajee Webtips Q & A forum for searching OR asking questions OR helping programmers with answers on these extensions and plugins. For asking a question click here. Select the appropriate question category (i.e. Krajee Plugins) and choose this current page plugin in the question related to field.

The comments and discussion section below are intended for generic discussions or feedback for this plugin. Developers may not be able to search or lookup here specific questions or tips on usage for this plugin.

 
visitors to Krajee Jquery Plugins since 22-May-2017