首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 上傳類別設計:支援單檔、批次、遠端抓取

     編輯:PHP 相關知識

物件導向封裝上傳邏輯

將上傳功能封裝為可重用類別,能統一錯誤處理、支援多種來源(本機、批次、遠端 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');
?>

設計亮點與擴充建議

  • 單一職責:各方法專注單一來源,易於測試與維護
  • 錯誤收集:陣列累積錯誤,支援批次操作後統一回報
  • 命名策略:預設時間戳,支援自訂輸出名稱,可擴充為 UUID、雜湊值
  • 遠端抓取:支援爬蟲、圖片代理、CDN 同步等場景

生產環境必加功能

  1. MIME/副檔名白名單驗證
  2. 檔案大小限制參數化
  3. 圖片處理整合(縮圖、水印、壓縮)
  4. 儲存驅動抽象化(本地、S3、FTP、資料庫 Blob)
  5. 上傳事件鉤子(前/後置處理、日誌、通知)
  6. 分塊上傳狀態管理(支援斷點續傳)

這個類別架構為建構企業級檔案管理系統奠定基礎,可根據專案需求逐步擴充。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved