Upload file with uploading progress
- index.php
<script type="text/javascript">
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
var formdata = new FormData();
formdata.append("file1",file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress",progressHandler,false);
ajax.addEventListener("load",completeHandler,false);
ajax.addEventListener("error",errorHandler,false);
ajax.addEventListener("abort",abortHandler,false);
ajax.open("POST","server_page.php");
ajax.send(formdata);
}
function progressHandlere(vent){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+"bytes of "+event.total;
var persent = (event.loaded/event.total)*100;
_("progressBar").value = Math.round(persent);
_("status").innerHTML = Math.round(persent)+"% uploaded...please wait.";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "Upload failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload aborted";
}
</script>
<body>
<form id="uploadForm" action="" method="post" enctype="multipart/form-data">
<input type="file" name="file1" id="file1"><br/>
<input type="button" value="Upload File" onclick="uploadFile()"><br/>
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<span id="status"></span>
<p id="loaded_n_total"></p>
</form>
</body>
- server_page.php
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLocation = $_FILES['file1']["tmp_name"]; //File in the php tmp folder
$fileType = $_FILES['file1']['type']; //The type of file it is
$fileSize = $_FILES['file1']['size']; // File size in byte
$fileErrorMsg = $_FILES['file1']['error']; // 0 for false 1 for true
if(!$fileTmpLocation){
echo "Error : Please browse for a file before clicking the upload button";
exit();
}
if(move_uploaded_file($fileTmpLocation, "upload/$fileName")){
echo "$fileName upload is completed";
}else{
echo "move_uploaded_file() function is failed";
}
Comments
Post a Comment