Ajax Image Upload

Ajax Image Upload With Progress Bar using PHP

Today, i am showing how to upload image with progress bar using PHP and AJAX.

Step 1 : First of all you have to create any HTML file for writing HTML, CSS and JS code, Basically, Client side code.

Let say file name is image_upload.html

code will look like..

<!doctype html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="//malsup.github.com/jquery.form.js"></script>
<style>
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
#progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
#bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
#percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>Ajax File Upload Demo</h1>
<form id="myForm" action="image_upload.php" method="post" enctype="multipart/form-data">
<input type="file" size="60" name="file">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
</div>
<br/>
<div id="message"></div>
<script>
$(function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$("#message").html("<font color='green'>"+response.responseText+"</font>");
},
error: function()
{
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
});
</script>
</body>
</html>

Step 2 :
Create php file and use following code. This code is for upload image with PHP code.
Let say file name is image_upload.php


<!?php if(isset($_FILES["file"])) { //Filter the file types , if you want. if ($_FILES["file"]["error"] --> 0)
{
echo "Error: " . $_FILES["file"]["error"] . "";
}else{
move_uploaded_file($_FILES["file"]["tmp_name"],'upload/'. $_FILES["file"]["name"]);
echo "Uploaded File :".$_FILES["file"]["name"];
}
}?>

Now, Upload this to you PHP enabled server. I think this will help you.

Note: “upload” folder must have 777 permission.

This entry was posted in Development, PHP and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

Human Verification: In order to verify that you are a human and not a spam bot, please enter the answer into the following box below based on the instructions contained in the graphic.