DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML5詳解
動手做 HTML5 檔案上傳:從前端串流到 PHP 接收
編輯:HTML5詳解     

以下以 xheditor 的實作為例,說明如何用 HTML5 把多檔上傳與進度回報串起來。

前端上傳邏輯

表單部分沿用一般的檔案選擇欄位,核心則是這段 JavaScript:

this.Html5Upload=function(inputname,fromfiles,tourl,callback,onProgress)
var xhr,i=0,count=fromfiles.length,allLoaded=0,allSize=0,_this=this;
for(var j=0;j<count;j++)allSize+=fromfiles[j].fileSize;
this.remove=function(){if(xhr){xhr.abort();xhr=null;}}
this.uploadNext=function(sText)
if(sText)// 當前檔案上傳完成
allLoaded+=fromfiles[i-1].fileSize;
returnProgress(0);
if((!sText||(sText&&callback(sText,i==count)==true))&&i<count)postFile(fromfiles[i++],tourl,_this.uploadNext,function(loaded){returnProgress(loaded);});
this.start=function(){_this.uploadNext();}
function postFile(fromfile,tourl,callback,onProgress)
xhr = new XMLHttpRequest(),upload=xhr.upload;
xhr.onreadystatechange=function(){if(xhr.readyState==4)callback(xhr.responseText);};
if(upload)upload.onprogress=function(ev){onProgress(ev.loaded);};
else onProgress(-1);//不支援進度
xhr.open("POST", tourl);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Content-Disposition', 'attachment; name="'+inputname+'"; filename="'+fromfile.fileName+'"');
if(xhr.sendAsBinary)xhr.sendAsBinary(fromfile.getAsBinary());
else xhr.send(fromfile);
function returnProgress(loaded){if(onProgress)onProgress({'loaded':allLoaded+loaded,'total':allSize});}

幾個設計重點:先加總所有檔案大小,逐檔序列上傳,透過 xhr.upload.onprogress 取得單檔進度,再換算成整體百分比;若瀏覽器不支援進度事件,就回傳 -1 讓前端自行降級。

觀察到的請求標頭

Content-Type: application/octet-stream
Content-Disposition: attachment; name="filedata"; filename="397913361.gif"

檔名與欄位名稱是靠 Content-Disposition 傳遞的,這也是伺服器端解析的依據。

PHP 端接收

if(isset($_SERVER['HTTP_CONTENT_DISPOSITION']))//Html5 上傳
if(preg_match('/attachment;\s+name="(.+?)";\s+filename="(.+?)"/i',$_SERVER['HTTP_CONTENT_DISPOSITION'],$info))
$temp_name=ini_get("upload_tmp_dir").'\\'.date("YmdHis").mt_rand(1000,9999).'.tmp';
file_put_contents($temp_name,file_get_contents("PHP://input"));
$size=filesize($temp_name);
$_FILES[$info[1]]=array('name'=>$info[2],'tmp_name'=>$temp_name,'size'=>$size,'type'=>'','error'=>0);

做法是用正則從標頭中抓欄位名與檔名,把二進位串流寫進暫存檔,再偽造出一個 $_FILES 結構。

一個容易踩到的坑

偽造完成後,後續就能沿用一般 PHP 上傳的處理流程。但要注意:此時 is_uploaded_file() 會回傳 false,move_uploaded_file() 也隨之失效,這時請改用 rename() 來搬移檔案。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved