Skip to main content

Multiple file upload using ajax with progress bar


            Uploading multiple files using ajax makes a pleasant feeling to the user. It makes even more happier if upload progress status is printed with percentage.

            In this blog, you will make a file upload form using ajax with file upload progress bar.

Prerequisites :

1) Javascript supported browser
2) LAMP Server / XAMPP Server

Code :

index.html

<!DOCTYPE html>

<html>

<head>

    <title>Multiple File Upload using Ajax</title>

    <link rel="stylesheet" type="text/css" href="style.css">

    <script src="//code.jquery.com/jquery-1.10.2.min.js"></script>

</head>

<body>

    <div>

        <form action="action.php" method="post" enctype="multipart/form-data" id="multiple-upload-form">

            <input type="button" id="select-file-btn" value="Select Files" onclick="document.getElementById('files').click(); return false;" />

            <input type="submit" id="file-upload-btn" name="file_upload_btn" value="Upload">

            <input type="file" id="files" name="files[]" multiple="" style="visibility: hidden;">

            <br><br>

            <div class="file-bar">

                <span class="file-bar-fill" id="file-bar-fill-id"><span class="file-bar-fill-text" id="file-bar-fill-text-id"></span></span>

            </div>

            <script type="text/javascript">
                var app = app || {};

                (function(o) {

                    "use strict";

                    var ajax, getFormData, setProgress;

                    ajax = function(data) {

                        var xmlhttp = new XMLHttpRequest(),
                            uploaded;

                        xmlhttp.addEventListener('readystatechange', function() {

                            if (this.readyState == 4) {

                                if (this.status == 200) {

                                    uploaded = JSON.parse(this.response);

                                    if (typeof o.options.finished === 'function') {

                                        o.options.finished(uploaded);

                                    }

                                } else {

                                    if (typeof o.options.error === 'function') {

                                        o.options.error();

                                    }

                                }

                            }

                        });

                        xmlhttp.upload.addEventListener("progress", function(event) {

                            var percent;

                            if (event.lengthComputable === true) {

                                percent = Math.round((event.loaded / event.total) * 100);

                                setProgress(percent);

                            }

                        });

                        if (o.options.progressBar !== undefined) {

                            o.options.progressBar.style.width = 0;

                        }

                        if (o.options.progressText !== undefined) {

                            o.options.progressText.innerText = 0;

                        }

                        xmlhttp.open("post", o.options.processor);

                        xmlhttp.send(data);

                    };

                    getFormData = function(source) {

                        var data = new FormData(),
                            i;

                        if (source.length <= 0) {

                            return false;

                        } else {

                            for (i = 0; i < source.length; i++) {

                                data.append('files[]', source[i]);

                            }

                            return data;

                        }

                    };

                    setProgress = function(value) {

                        if (o.options.progressBar !== undefined) {

                            o.options.progressBar.style.width = value ? value + "%" : 0;

                        }

                        if (o.options.progressText !== undefined) {

                            o.options.progressText.innerText = value ? value + "%" : 0;

                        }

                    };

                    o.uploader = function(options) {

                        o.options = options;

                        if (o.options.files !== undefined) {

                            var imageFormDataValue = getFormData(o.options.files.files);

                            if (imageFormDataValue === false)

                            {

                                alert("No Files Selected");

                                document.getElementById("file-upload-btn").disabled = false;

                                document.getElementById("select-file-btn").disabled = false;

                            } else

                            {

                                ajax(imageFormDataValue);

                            }

                        }

                    };

                }(app));

                document.getElementById("file-upload-btn").addEventListener("click", function(e) {

                    e.preventDefault();

                    document.getElementById("file-upload-btn").setAttribute("disabled", "true");

                    document.getElementById("select-file-btn").setAttribute("disabled", "true");

                    var f = document.getElementById('files'),

                        pb = document.getElementById('file-bar-fill-id'),

                        pt = document.getElementById('file-bar-fill-text-id');

                    app.uploader({

                        files: f,

                        progressBar: pb,

                        progressText: pt,

                        processor: "action.php",

                        finished: function(data) {

                            document.getElementById("file-upload-btn").disabled = false;

                            document.getElementById("select-file-btn").disabled = false;

                            if (data.status === true) {

                                alert(data.data);

                            }

                        },

                        error: function() {

                            alert("Error occured. Try Again after page reload.");

                        }

                    });

                });
            </script>

        </form>

    </div>

</body>

</html>
style.css

.file - bar {

        width: 40 % ;

        background: #eee;

        padding: 3 px;

        margin - bottom: 10 px;

        box - shadow: inset 0 1 px 3 px rgba(0, 0, 0, 0.2);

        border - radius: 3 px;

        box - sizing: border - box;

    }

    .file - bar - fill {

        height: 20 px;

        display: block;

        background: cornflowerblue;

        width: 0;

        border - radius: 3 px;

        transition: width 0.8 s ease;

    }

    .file - bar - fill - text {

        color: #fff;

        padding: 3 px;

    }
action.php

<?php

set_time_limit(0);

if(count($_FILES["files"])>0)

{

$success = 0;

$failed = 0;

foreach ($_FILES["files"]["error"] as $key => $value)

{

if(empty($value))

{

if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], __DIR__."/uploads/".uniqid()."_".$_FILES["files"]["name"][$key]))

{

$success++;

}

else

{

$failed++;

}

}

else

{

$failed++;

}

}

$data = "";

if($success>0)

$data .= $success." files uploaded. ";

if($failed>0)

$data .= $failed." files failed to upload";

$response = array("status" => true, "data" => $data );

echo json_encode($response);

}

?>
Create a sub-folder named "uploads" in your project directory.

You can download code here

Comments

Popular posts from this blog

Implementing Client Side WebRTC using Sipml5 javascript

Step 1:

Download and require Sipml5 library function.

Step 2:

Initialize sipml5 Engine in your web page :

var readyCallback = function(e) {
// function called when sipml is successfully initialised.
createSipStack(); // calling this function to create sip stack(see below)
};

var errorCallback = function(e) {
// function called when error occured during sipml initialisation.
};

SIPml.init(readyCallback, errorCallback);

Step 3:

Create Sip Stack :-
Sip Stack is an object that must be created before making/receiving call and sms. Creating Sip stack is an asynchronous process, so you need to create an event listener function to get state change notification.

var sipStack;

function EventListener(e) {

/*
* e.type ;type of event listener
* e.session ; current event session
* e.getSipResponseCode() ; event response code
* e.description ; event description
*/

if(e.type == 'started'){
// successfully started the stack.
register();
} else if(e.type == 'i_new_call'){
// when new incoming call comes.
      …

Setup Asterisk 13 with FreePBX 13 in CentOS 7

Launch CentOS 7 AWS Ec2 InstanceLog in to your aws consoleGo to ec2 management page and click Launch Instance on Instance pageIn Choose AMI step, go to AWS MarketPlace tab and search CentOS 7 on search field. List of centos 7 ami's will be available.Select CentOS 7 (x86_64) ami which is free tier eligible. Select your instance type and click configure instance. Keep default values from Configure Instance to Add Tags stepsIn configure security group, create a security group which allow minimum ports openSSH : port 22HTTP : port 80Custom UDP Rule : 10000-20000 (if you are giving RTP ports 10000-20000)Custom UDP Rule : 5060 (ChanSIP port)Custom TCP Rule : 5060 (ChanSIP Port)Click Launch Instance. Select your key file and accept terms to launch instance.
Setup CentOS Server SSH into newly created CentOS server with username centos and your key file.Update all existing packagessudo yum update -yNow start http service(you can access your server via browser by going to your server ip addres…

Twilio - Record a complete incoming call

Currently, Twilio services does not provide to record the whole incoming call. Only dial initiated within the incoming call can be recorded. But in day to day life, there are many occasion we need to record the whole incoming call such as an ivr call or a customer service call. So, by taking the twilio feature that child call can be recorded, i have developed a call flow using two twilio numbers so that we can record the complete call from caller.
For demonstrating, i have created a small ivr. When caller calls twilio number. It will be asked a gather "whether he/she is interested in taking to our agent? if yes press one or not press two or just hangup". If caller press one, call will be redirected to an agent.

If we try above call method, we get only the recording of agent call. We misses what happened after twilio answer and before agent call. So to get whole call recording, i have developed another mechanism as below

When caller calls twilio number A, twilio will ans…