php進階——02 多檔案上傳
阿新 • • 發佈:2018-12-01
前言
使用MVC的思想去封裝一個多檔案上傳類,入口檔案為index.php,檢視檔案有single和group2個html檔案,controller有upload.class.php。
index.php
// 1.定義根目錄常量FILEROOT // 把路徑名裡的'\\'換成'/' define("FILEROOT",str_replace('\\','/',dirname(__FILE__))); // 2,引入檔案上傳處理類 require_once FILEROOT.'/controller/Upload.class.php'; // 3.例項化上傳物件 $upload = new Upload(); // 4.初始化action引數 // 引數為空 或者 不屬於[show,upload],設為show,否則設為upload $action = empty($_GET['action']) || !in_array($_GET['action'],array('show','upload')) ? 'show' : $_GET['action']; // 5.如果show,就顯示頁面;如果是upload,就處理使用者上傳檔案 if($action == 'show'){ $type = empty($_GET['type']) || !in_array($_GET['type'],array('single','group')) ?'single':$_GET['type']; $upload -> showPage($type); }elseif($action == 'upload'){ $upload -> handleUpload(); }
single.html(獨立名稱)
<form action="index.php?action=upload" method="post" enctype="multipart/form-data"> <!-- 這個用來識別是獨立名稱,還是名稱組--> <input type="hidden" name="type" value="single"> <!-- name不一樣 --> <div class="form-group">one <input type="file" name="one" class="form-control"> </div> <div class="form-group">two <input type="file" name="two" class="form-control"> </div> <div class="form-group">three <input type="file" name="three" class="form-control"> </div> <div class="form-group"> <input type="submit" value="上傳" class="btn btn-primary"> </div> </form>
group.html(名稱組)
<!-- 注意,這裡的action在問號後帶引數 --> <form action="index.php?action=upload" method="post" enctype="multipart/form-data"> <!-- 這個用來識別是獨立名稱,還是名稱組--> <input type="hidden" name="type" value="group"> <!-- name一樣 --> <div class="form-group">upload[] <input type="file" name="upload[]" class="form-control"> </div> <div class="form-group">upload[] <input type="file" name="upload[]" class="form-control"> </div> <div class="form-group">upload[] <input type="file" name="upload[]" class="form-control"> </div> <div class="form-group"> <input type="submit" value="上傳" class="btn btn-primary"> </div> </form>
獨立名稱、名稱組的區別
獨立名稱$_FILES
資料結構
名稱組$_FILES
資料結構
upload.class.php
// 檔案上傳處理類
class Upload
{
// 1.用於儲存多個檔案的資訊
private $file = array();
// 2.儲存上傳結果
private $return;
// 3.顯示上傳頁面函式
public function showPage($templateName)
{
echo file_get_contents(FILEROOT.'/view/'.$templateName.'.html');
}
// 4.處理上傳檔案主函式
public function handleUpload()
{
// 獲取檔案資訊並處理
$this -> fixFiles();
}
// 5.獲取上傳檔案資訊並處理 函式
private function fixFiles()
{
// 獨立名稱
if($_POST['type'] == 'single'){
$this -> file = $_FILES;
// 名稱組
}else{
foreach($_FILES as $name => $info){
foreach($info as $attr => $values){
foreach($info as $attr => $values){
$this->file = [$name.$index]['attr'] = $value;
}
}
}
}
}