範例程式碼:
代碼如下 |
複製代碼 |
<form action="" method="post" enctype="multipart/form-data" > <input type="file" name="uploadfile[]"> 命名必是這樣有"[]" <input type="file" name="uploadfile[]"> |
//設定允許使用者上傳的檔案類型。
$type = array('gif', 'jpg', 'png', 'zip', 'rar');
$upload = new uploadfile($_files['uploadfile'], '/', 1024*1024, $type);
參數說明:1:表單的檔案,2:上傳目錄,3:支援檔案大小,4:允許檔案類型
$icount = $upload->upload();
if($icount > 0) { //上傳成功
print_r($upload->getsaveinfo());
*/
class uploadfile {
var $postfile = array(); // 使用者上傳的檔案
var $custompath = ""; // 自訂檔案上傳路徑
var $maxsize = ""; // 檔案最大尺寸
var $lasterror = ""; // 最後一次出錯資訊
var $allowtype = array('gif', 'jpg', 'png', 'zip', 'rar', 'txt', 'doc', 'pdf');
var $endfilename = ""; // 最終儲存的檔案名稱
var $saveinfo = array(); // 儲存檔案的最終資訊
var $root_dir = ""; // 項目在硬碟上的位置
/**
* 建構函式
* @access public
*/
代碼如下 |
複製代碼 |
function uploadfile($arrfile, $path="_", $size = 2097152, $type = 0) { $this->postfile = $arrfile; $this->custompath = $path == "_" ? "" : $path ; $this->maxsize = $size; if($type!=0) $this->allowtype = $arrfile; $this->root_dir = $_server['document_root']; $this->_mkdir($this->custompath); } |
/**
* 檔案上傳的核心代碼
* @access public
* @return int 上傳成功檔案數
*/
代碼如下 |
複製代碼 |
function upload() { $ilen = sizeof($this->postfile['name']); for($i=0;$i<$ilen;$i++){ if ($this->postfile['error'][$i] == 0) { //上傳時沒有發生錯誤 //取當前檔案名稱、臨時檔案名稱、大小、副檔名,後面將用到。 $sname = $this->postfile['name'][$i]; $stname = $this->postfile['tmp_name'][$i]; $isize = $this->postfile['size'][$i]; $stype = $this->postfile['type'][$i]; $sextn = $this->_getextname($sname); //檢測當前上傳檔案大小是否合法。 if($this->_checksize){ $this->lasterror = "您上傳的檔案[".$sname."],超過系統支援大小!"; $this->_showmsg($this->lasterror); continue; } if(!is_uploaded_file($stname)) { $this->lasterror = "您的檔案不是通過正常途徑上傳!"; $this->_showmsg($this->lasterror); continue; } $_filename = basename($sname,".".$sextn)."_".time().".".$sextn; $this->endfilename = $this->custompath.$_filename; if(!move_uploaded_file($stname, $this->root_dir.$this->endfilename)) { $this->lasterror = $this->postfile['error'][$i]; $this->_showmsg($this->lasterror); continue; } //儲存當前檔案的有關資訊,以便其它程式調用。 $this->save_info[] = array("name" => $sname, "type" => $sextn, "size" => $isize, "path" => $this->endfilename); } } return sizeof($this->save_info); } |