There have been queries and requests from many folks who wish to learn implementing AJAX uploads with the bootstrap-fileinput jQuery plugin. How does one build the server code (e.g. PHP) for parsing the AJAX response and sending data back to the plugin? This webtip mentions a PHP server side processing example for using the bootstrap-fileinput plugin to process your ajax based uploads.
About bootstrap-fileinput
The bootstrap-fileinput jQuery plugin by Krajee is an advanced HTML 5 file input designed using Bootstrap 3.x CSS styles. It is a simple yet powerful file management tool and solution for web developers that utilizes HTML 5 and CSS 3 features (supported by most modern browsers). In addition to advanced styles & layouts, the plugin offers file preview for various files, multiple selection including drag & drop, ajax based uploads with progress bar, setting initial previews and deletes and more.
Pre-requisites
Ensure all the pre-requisites for the bootstrap-fileinput jQuery plugin are followed and adhered to. You must have the bootstrap CSS and jQuery library loaded before you run the other scripts below.
Input Markup (HTML)
Let’s consider you have the following markup to initialize the input. The scenario considered is ajax based upload of multiple images. Your markup can be as simple as below (note the id
and name
attributes).
<input id="images" name="images[]" type="file" multiple>
However, in many cases you may have other form fields or additional data you may need to submit. Let’s consider you have the following additional fields in your form.
<input id="userid" name="userid" type="hidden">
<input id="username" name="username" type="text">
Initialize Plugin (Javascript)
Let’s consider a simple scenario of uploading files via Ajax. You will need to setup the javascript to initialize the bootstrap fileinput plugin. Note that the examples here uses jQuery. You would like to send additional form data when the files are uploaded (i.e. user_id
and user_name
). You can setup all of these as mentioned below. By default the plugin will upload in asynchronous mode through parallel ajax calls. You can control that through uploadAsync
property.
$(document).on("ready", function() {
$("#images").fileinput({
uploadAsync: false,
uploadUrl: "/path/to/upload.php" // your upload server url
uploadExtraData: function() {
return {
userid: $("#userid").val(),
username: $("#username").val()
};
}
});
});
Server Code (PHP)
Let’s look at the server code upload.php
as mentioned above that will receive and process the data.
// upload.php
// 'images' refers to your file input name attribute
if (empty($_FILES['images'])) {
echo json_encode(['error'=>'No files found for upload.']);
// or you can throw an exception
return; // terminate
}
// get the files posted
$images = $_FILES['images'];
// get user id posted
$userid = empty($_POST['userid']) ? '' : $_POST['userid'];
// get user name posted
$username = empty($_POST['username']) ? '' : $_POST['username'];
// a flag to see if everything is ok
$success = null;
// file paths to store
$paths= [];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
$ext = explode('.', basename($filenames[$i]));
$target = "uploads" . DIRECTORY_SEPARATOR . md5(uniqid()) . "." . array_pop($ext);
if(move_uploaded_file($images['tmp_name'][$i], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
}
// check and process based on successful status
if ($success === true) {
// call the function to save all data to database
// code for the following function `save_data` is not
// mentioned in this example
save_data($userid, $username, $paths);
// store a successful response (default at least an empty array). You
// could return any additional response info you need to the plugin for
// advanced implementations.
$output = [];
// for example you can get the list of files uploaded this way
// $output = ['uploaded' => $paths];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
// delete any uploaded files
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
Summary
That’s about a basic setup you need to do to upload files via ajax and the plugin should process it. Note, that for your practical cases you may need to tweak various other settings and add to this basic setup above. You may also need to control various other properties of the plugin to make it work the way you want for your entire application – like uploadAsync
, initialPreview
, initialPreviewDelete
etc. Similarly, you can use the various events in the plugin to trigger or perform additional actions – e.g. filepreupload
, fileuploaded
etc.
The post Ajax based file uploads using FileInput plugin appeared first on Krajee Web Tips.