PHP+Ajax實現上傳檔案進度條動態顯示進度功能

來源:互聯網
上載者:User
這篇文章主要介紹了PHP+Ajax實現上傳檔案進度條動態顯示進度功能,通過ajax實現主介面,php處理上傳檔案,具體執行個體代碼大家一起看看吧

說個前提:PHP設定檔中規定預設上傳檔案大小限制2M以下,如需上傳大檔案需同時更改php.ini中的upload_max_filesizemax_execution_time以及post_max_size的值。

主介面以及Ajax實現:index.html

<!DOCTYPE html> <html lang="en"> <head>   <meta charset="UTF-8">   <title>上傳檔案</title>   <script type="text/javascript">     function sub() {       var obj = new XMLHttpRequest();       obj.onreadystatechange = function() {         if (obj.status == 200 && obj.readyState == 4) {           document.getElementById('con').innerHTML = obj.responseText;         }       }       // 通過Ajax對象的upload屬性的onprogress事件感知當前檔案上傳狀態       obj.upload.onprogress = function(evt) {         // 上傳附件大小的百分比         var per = Math.floor((evt.loaded / evt.total) * 100) + "%";         // 當上傳檔案時顯示進度條         document.getElementById('parent').style.display = 'block';         // 通過上傳百分比設定進度條樣式的寬度         document.getElementById('son').style.width = per;         // 在進度條上顯示上傳的進度值         document.getElementById('son').innerHTML = per;       }       // 通過FormData收集零散的檔案上傳資訊       var fm = document.getElementById('userfile3').files[0];       var fd = new FormData();       fd.append('userfile', fm);       obj.open("post", "upload.php");       obj.send(fd);     }   </script>   <style type="text/css">     #parent {       width: 200px;       height: 20px;       border: 2px solid gray;       background: lightgray;       display: none;     }     #son {       width: 0;       height: 100%;       background: lightgreen;       text-align: center;     }   </style> </head> <body>   <h2>Ajax實現進度條檔案上傳</h2>   <p id="parent">     <p id="son"></p>   </p>   <p id="con"></p>   <input type="file" name="userfile" id="userfile3"><br><br>   <input type="button" name="btn" value="檔案上傳" onclick="sub()"> </body> </html>

php處理上傳檔案:upload.php

<?php    // 上傳檔案進行簡單錯誤過濾   if ($_FILES['userfile']['error'] > 0) {     exit("上傳檔案有錯".$_FILES['userfile']['error']);   }   // 定義存放上傳檔案的真實路徑   $path = './upload/';   // 定義存放上傳檔案的真實路徑名字   $name = $_FILES['userfile']['name'];   // 將檔案的名字的字元編碼從UTF-8轉成GB2312   $name = iconv("UTF-8", "GB2312", $name);   // 將上傳檔案移動到指定目錄檔案中   if (move_uploaded_file($_FILES['userfile']['tmp_name'], $path.$name)) {     echo "檔案上傳成功";   } else {     echo "檔案上傳失敗";   }  ?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.