This example uses jquery.form.js, please go to the demo page to view
CSS Code
Copy Code code as follows:
<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>
Xml/html Code
Copy Code code as follows:
<form id= "MyForm" action= "upload.php" method= "post" enctype= "Multipart/form-data" >
<input type= "File" size= "Name=" "MyFile" >
<input type= "Submit" value= "Ajax File Upload" >
</form>
<div id= "Progress" >
<div id= "Bar" ></div>
<div id= "percent" >0%</div >
</div>
<div id= "Message" ></div>
JavaScript Code
Copy Code code as follows:
<script>
$ (document). Ready (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>
upload.php
Copy Code code as follows:
<?php
$output _dir = ". /upload/";
if (Isset ($_files["myfile"]))
{
Filter the file types, if you want.
if ($_files["myfile"] ["error"] > 0)
{
echo "Error:". $_files["File" ["Error"]. "<br>";
}
Else
{
Move the uploaded file to uploads folder;
Move_uploaded_file ($_files["myfile"] ["Tmp_name"], $output _dir "$_files["] ["name"]);
echo "uploaded File:". $_files["MyFile" ["Name"];
}
}
?>