欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php ajax实现文件上传进度条

程序员文章站 2023-12-17 09:09:04
本实例是关于php文件上传时进度条的实现,主要采用ajax技术,另外还运用了html5,有需要的朋友可以研究一下。 本实例有两个文件: upload_form.html...

本实例是关于php文件上传时进度条的实现,主要采用ajax技术,另外还运用了html5,有需要的朋友可以研究一下。
本实例有两个文件:

upload_form.html:

<!doctype html>
<html>
<head>
<script>
function _(el){
  return document.getelementbyid(el);
}
function uploadfile(){
  var file = _("file1").files[0];
  // alert(file.name+" | "+file.size+" | "+file.type);
  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", "file_upload_parser.php");
  ajax.send(formdata);
}

function progresshandler(event){
  _("loaded_n_total").innerhtml = "uploaded "+event.loaded+" bytes of "+event.total;
  var percent = (event.loaded / event.total) * 100;
  _("progressbar").value = math.round(percent);
  _("status").innerhtml = math.round(percent)+"% 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>
</head>
<body>
<h2>html5 file upload progress bar tutorial</h2>
<form id="upload_form" enctype="multipart/form-data" method="post">
 <input type="file" name="file1" id="file1"><br>
 <input type="button" value="upload file" onclick="uploadfile()">
 <progress id="progressbar" value="0" max="100" style="width:300px;"></progress>
 <h3 id="status"></h3>
 <p id="loaded_n_total"></p>
</form>
</body>
</html>

file_upload_parser.php:

<?php
$filename = $_files["file1"]["name"]; // the file name
$filetmploc = $_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 bytes
$fileerrormsg = $_files["file1"]["error"]; // 0 for false... and 1 for true
if (!$filetmploc) { // if file not chosen
  echo "error: please browse for a file before clicking the upload button.";
  exit();
}
if(move_uploaded_file($filetmploc, "test_uploads/$filename")){
  echo "$filename upload is complete";
} else {
  echo "move_uploaded_file function failed";
}
?>

以上就是本文的全部内容,希望对大家的学习有所帮助。

上一篇:

下一篇: