In this example, jquery. form. js is used. Please go to the demo page to view
CSS Code
Copy codeThe Code is 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 codeThe Code is as follows:
<Form id = "myForm" action = "upload. php" method = "post" enctype = "multipart/form-data">
<Input type = "file" size = "60" name = "myfile">
<Input type = "submit" value = "Ajax File Upload">
</Form>
<Div id = "progress">
<Div id = "bar"> </div>
& Lt; div id = "percent" & gt; 0% & lt;/div & gt;
</Div>
<Div id = "message"> </div>
JavaScript Code
Copy codeThe Code is as follows:
<Script>
$ (Document). ready (function ()
{
Var options = {
BeforeSend: function ()
{
$ ("# Progress"). show ();
// Clear everything
$ ("# Bar"). width ('0% ');
$ ("# Message" pai.html ("");
$ ("# Percent" 2.16.html ("0% ");
},
UploadProgress: function (event, position, total, percentComplete)
{
$ ("# Bar"). width (percentComplete + '% ');
$ ("# Percent" 2.16.html (percentComplete + '% ');
},
Success: function ()
{
$ ("# Bar"). width ('20140901 ');
$ ("# Percent" 2.16.html ('20140901 ');
},
Complete: function (response)
{
$ ("# Message" 2.16.html ("<font color = 'green'>" + response. responseText + "</font> ");
},
Error: function ()
{
$ ("# Message" 2.16.html ("<font color = 'red'> ERROR: unable to upload files </font> ");
}
};
$ ("# MyForm"). ajaxForm (options );
});
</Script>
Upload. php
Copy codeThe Code is 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 ["myfile"] ["name"]);
Echo "Uploaded File:". $ _ FILES ["myfile"] ["name"];
}
}
?>