前言
使用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;
}
}
}
}
}