將上傳功能封裝為可重用類別,能統一錯誤處理、支援多種來源(本機、批次、遠端 URL)、提供一致介面。本文展示一個具備單檔/批次上傳、遠端抓取、自動命名、錯誤收集功能的上傳類別架構。
<?php
class MyFrame_Upload {
protected $uploadPath = 'uploadFile/';
protected $fullPath = '';
protected $errorMessages = [];
protected $debug = false;
public function __construct($uploadPath = '') {
if ($uploadPath) $this->uploadPath = rtrim($uploadPath, '/') . '/';
}
/** 單檔上傳 */
public function fromLocal($fileArray, $outputName = '') {
if ($fileArray['error'] > 0) {
$this->setError($fileArray['error']);
return false;
}
$outputName = $outputName ?: date('YmdHis');
$ext = $this->getExt($fileArray['name']);
$fileName = $this->uploadPath . $outputName . $ext;
if (is_uploaded_file($fileArray['tmp_name'])) {
if (move_uploaded_file($fileArray['tmp_name'], $fileName)) {
$this->fullPath = $fileName;
return $fileName;
}
$this->errorMessages[] = '檔案移動失敗';
return false;
}
$this->errorMessages[] = '非合法上傳檔案';
return false;
}
/** 批次上傳 */
public function fromLocalBatch($keepSource = false, $outputNames = []) {
$results = [];
$i = 0;
foreach ($_FILES as $key => $file) {
$name = ($keepSource && isset($outputNames[$i])) ? $outputNames[$i] : '';
$results[] = $this->fromLocal($file, $name);
$i++;
}
return $results;
}
/** 遠端 URL 抓取儲存 */
public function fromNet($url, $outputName = '', $keepSource = false) {
$outputName = $outputName ?: date('YmdHis');
$ext = $this->getExt($url);
$fileName = $this->uploadPath . $outputName . $ext;
$content = @file_get_contents($url);
if ($content === false) {
$this->errorMessages[] = '遠端檔案讀取失敗';
return false;
}
if (file_put_contents($fileName, $content) !== false) {
$this->fullPath = $fileName;
return $fileName;
}
$this->errorMessages[] = '遠端檔案儲存失敗';
return false;
}
/** 取得錯誤訊息 */
public function getErrors() {
return $this->errorMessages;
}
/** 取得副檔名 */
protected function getExt($filename) {
return '.' . pathinfo($filename, PATHINFO_EXTENSION);
}
/** 錯誤碼對應訊息 */
protected function setError($code) {
$messages = [
UPLOAD_ERR_INI_SIZE => '超過 php.ini upload_max_filesize',
UPLOAD_ERR_FORM_SIZE => '超過表單 MAX_FILE_SIZE',
UPLOAD_ERR_PARTIAL => '檔案上傳不完整',
UPLOAD_ERR_NO_FILE => '未選擇檔案',
];
$this->errorMessages[] = $messages[$code] ?? "未知錯誤碼: $code";
}
}
?>
<?php
require 'MyFrame_Upload.php';
$uploader = new MyFrame_Upload('uploads/');
// 單檔上傳
$result = $uploader->fromLocal($_FILES['avatar'], 'user_avatar');
if ($result) {
echo "上傳成功: $result";
} else {
print_r($uploader->getErrors());
}
// 批次上傳
$results = $uploader->fromLocalBatch();
foreach ($results as $r) {
echo $r ? "成功: $r\n" : "失敗\n";
}
// 遠端抓取
$remote = $uploader->fromNet('https://example.com/image.jpg', 'remote_img');
?>
這個類別架構為建構企業級檔案管理系統奠定基礎,可根據專案需求逐步擴充。