本文實例講述了PHP實現帶進度條的Ajax文件上傳功能。分享給大家供大家參考,具體如下:
之前分享了一篇關于 php使用FileApi實現Ajax上傳文件 的文章,里面的Ajax文件上傳是不帶進度條的,今天分享一篇關于帶進度條的Ajax文件上傳文章。
效果圖:
項目結構圖:
12-progress-upload.html文件:
頁面中主要有一個上傳文件控件,有文件被選擇時響應selfile()方法,接著利用js讀取上傳文件、創建FormData對象和xhr對象,利用xhr2的新標準,寫一個監聽上傳過程函數,請求11-fileApi.php文件。
<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>HTML5帶進度條的上傳功能</title> <link rel="stylesheet" href=""><script> function selfile(){ //js讀取上傳文件 var file = document.getElementsByTagName('input')[0].files[0]; //創建FormData對象 var fd = new FormData(); fd.append('pic',file); //ajax上傳文件 var xhr = new XMLHttpRequest(); xhr.open('POST','11-fileApi.php',true); //利用xhr2的新標準,為上傳過程,寫一個監聽函數 xhr.upload.onprogress = function(ev){ if(ev.lengthComputable){//文件長度可計算 var percent = 100*ev.loaded/ev.total;//計算上傳的百分比 document.getElementById('bar').style.width = percent + '%';//更改上傳進度 document.getElementById('bar').innerHTML = parseInt(percent)+'%';//顯示上傳進度 } } xhr.send(fd);//發送請求 }</script><style> #progress{ width:500px; height:30px; border:1px solid green; } #bar{ width:0%; height:100%; background-color: green; }</style></head><body> <h1>HTML5帶進度條的上傳功能</h1> <div id="progress"> <div id="bar"></div> </div> <input type="file" name="pic" onchange="selfile();" /></body></html>11-fileApi.php文件:
首先判斷是否有文件上傳,然后判斷文件上傳是否成功,最后移動文件至當前目錄下的upload目錄下,文件名不變。
<?php/** * fileApi實現Ajax上傳文件 * @author webbc */if(empty($_FILES)){ exit('no file');}if($_FILES['pic']['error'] !== 0){ exit('fail');}move_uploaded_file($_FILES['pic']['tmp_name'],'./upload/'.$_FILES['pic']['name']);?>
希望本文所述對大家PHP程序設計有所幫助。
新聞熱點
疑難解答
圖片精選