Upload files with progress bar using php and AJAX

No comments
Hello friends, In this tutorial, I am going to demonstrate you how to upload files in php with progress bar. As you know, there are many tutorials are available over the internet on the same topic but i am going to share easiest way to create file upload with ajax ( using XMLHttpRequest() ) and php.

So lets start. First we will create a file named index.php and put the below code into it.

<form id="uploadimg" action="upload-file.php" method="post" >
<label>Choose Image:</label>
<input name="myimg" id="myimg" type="file" class="imgcls" />
<br />
<input type="submit" id="btnSubmit" value="Submit" class="btn" />
<div id="progress-div"><div id="progress-bar"></div></div>
</form>

and style the page so it looks good. create a css file and name it style.css.

#progress-div{
border: #000000 1px solid;
padding: 0 0px;
margin: 5px 0px 20px 0px;
border-radius: 4px;
text-align: center;
width: 100%;
float: left;
}
#progress-status{}
#progress-bar{ 
background:#000;
height: 20px;
color: #FFFFFF;
width: 0%;
transition: width .3s;
}
.btn{
border-radius: 5px;
background: #E92A4F;
color: #fff;
font-weight: 600;
text-transform: uppercase;
border: none;
font-size: 12px;
padding: 7px 15px;
margin-top: 10px;
margin-bottom: 10px;
cursor: pointer;
display: inline-block;
}

Create another .php file tht will upload your files on your server and name it as upload-file.php.

<?php
if(!empty($_FILES)) {
if(is_uploaded_file($_FILES['myimg']['tmp_name'])) {
$sourcePath = $_FILES['myimg']['tmp_name'];
$targetPath = "images/".$_FILES['myimg']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
echo 'file uploaded successfully.';
}else{echo 'failed.';}
}
}
?>
Now its time to add JavaScript code that will hold our logic.

<script type="text/javascript">
       
 $( 'form' ).submit(function ( e ) {
 var data, xhr;
    data = new FormData();
    data.append( 'myimg', $( '#myimg' )[0].files[0] );
    xhr = new XMLHttpRequest();
    xhr.open( 'POST', 'upload-file.php', true );
    xhr.upload.onloadstart = function (e) {
     $("#progress-bar").width('0%');
    };
 xhr.upload.onprogress = function (e) {
        if (e.lengthComputable) {
            var ratio = Math.floor((e.loaded / e.total) * 100) + '%';
            $("#progress-bar").width(ratio);
            $("#progress-bar").html('<div id="progress-status">' + ratio +'</div>');
            if(ratio=='100%'){
            $("#progress-bar").html('<div id="progress-status">Completed.</div>');
            }
        }
        };
    xhr.send( data );
 e.preventDefault();
 
});
                  
</script>
and finally here is complete working example.

<!doctype html>

<html lang="en">
<head>
    <meta charset="utf-8" />
 <title>Title Goes Here</title>
 <script type="text/javascript" src="js/jquery.min.js"></script>
 <script type="text/javascript" src="js/jquery.form.min.js"></script>
 <link href="css/style.css" rel="stylesheet">
</head>
<body>
<div style="text-align:center;">
<h3>File upload with progress bar using php and jquery</h3>
<hr />
<form id="uploadimg" action="upload-file.php" method="post" >
<label>Choose Image:</label>
<input name="myimg" id="myimg" type="file" class="imgcls" />
<br />
<input type="submit" id="btnSubmit" value="Submit" class="btn" />
<div id="progress-div"><div id="progress-bar"></div></div>
</form>
</div>
<script type="text/javascript">
       
 $( 'form' ).submit(function ( e ) {
 var data, xhr;
    data = new FormData();
    data.append( 'myimg', $( '#myimg' )[0].files[0] );
    xhr = new XMLHttpRequest();
    xhr.open( 'POST', 'upload-file.php', true );
    xhr.upload.onloadstart = function (e) {
     $("#progress-bar").width('0%');
    };
 xhr.upload.onprogress = function (e) {
        if (e.lengthComputable) {
            var ratio = Math.floor((e.loaded / e.total) * 100) + '%';
            $("#progress-bar").width(ratio);
            $("#progress-bar").html('<div id="progress-status">' + ratio +'</div>');
            if(ratio=='100%'){
            $("#progress-bar").html('<div id="progress-status">Completed.</div>');
            }
        }
        };
    xhr.send( data );
 e.preventDefault();
 
});
                  
</script>
</body>
</html>


Is not it easy as i already said? Please do let me know in the comment box below. Thanks.

No comments :

Post a Comment