php ajax实现文件上传进度条

这篇文章主要介绍了php ajax实现文件上传进度条的相关资料,需要的朋友可以参考下,本实例是关于php文件上传时进度条的实现,主要采用ajax技术,另外还运用了html5,有需要的朋友可以研究一下。

本实例有两个文件:

upload_form.html:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script>
  5. function _(el){
  6. return document.getElementById(el);
  7. }
  8. function uploadFile(){
  9. var file = _("file1").files[0];
  10. // alert(file.name+" | "+file.size+" | "+file.type);
  11. var formdata = new FormData();
  12. formdata.append("file1", file);
  13. var ajax = new XMLHttpRequest();
  14. ajax.upload.addEventListener("progress", progressHandler, false);
  15. ajax.addEventListener("load", completeHandler, false);
  16. ajax.addEventListener("error", errorHandler, false);
  17. ajax.addEventListener("abort", abortHandler, false);
  18. ajax.open("POST", "file_upload_parser.php");
  19. ajax.send(formdata);
  20. }
  21. function progressHandler(event){
  22. _("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
  23. var percent = (event.loaded / event.total) * 100;
  24. _("progressBar").value = Math.round(percent);
  25. _("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
  26. }
  27. function completeHandler(event){
  28. _("status").innerHTML = event.target.responseText;
  29. _("progressBar").value = 0;
  30. }
  31. function errorHandler(event){
  32. _("status").innerHTML = "Upload Failed";
  33. }
  34. function abortHandler(event){
  35. _("status").innerHTML = "Upload Aborted";
  36. }
  37. </script>
  38. </head>
  39. <body>
  40. <h2>HTML5 File Upload Progress Bar Tutorial</h2>
  41. <form enctype="multipart/form-data" method="post">
  42. <input type="file" name="file1" ><br>
  43. <input type="button" value="Upload File" onclick="uploadFile()">
  44. <progress value="0" max="100" ></progress>
  45. <h3 ></h3>
  46. <p ></p>
  47. </form>
  48. </body>
  49. </html>

file_upload_parser.php:

  1. <?php
  2. $fileName = $_FILES["file1"]["name"]; // The file name
  3. $fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
  4. $fileType = $_FILES["file1"]["type"]; // The type of file it is
  5. $fileSize = $_FILES["file1"]["size"]; // File size in bytes
  6. $fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
  7. if (!$fileTmpLoc) { // if file not chosen
  8. echo "ERROR: Please browse for a file before clicking the upload button.";
  9. exit();
  10. }
  11. if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){
  12. echo "$fileName upload is complete";
  13. } else {
  14. echo "move_uploaded_file function failed";
  15. }
  16. ?>

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