提供一個可直接複製使用的 Upload 類別,支援檔案驗證、隨機命名、目錄自建、GD 庫等比例縮略圖生成。代碼結構清晰,適合學習參考或直接整合至專案。
圖片上傳測試
fieldName = $fieldName;
$this->fileInfo = $_FILES[$fieldName] ?? null;
}
public function upload() {
if (!$this->fileInfo) throw new Exception("無檔案上傳");
$this->checkError() || throw new Exception($this->errorMsg);
$this->checkMime() || throw new Exception($this->errorMsg);
$this->checkExt() || throw new Exception($this->errorMsg);
$this->checkSize() || throw new Exception($this->errorMsg);
$this->checkUpload() || throw new Exception($this->errorMsg);
$this->ensureDir();
$this->savePath = $this->uploadDir . '/' . $this->randName() . '.' . $this->ext;
if (!move_uploaded_file($this->fileInfo['tmp_name'], $this->savePath)) {
throw new Exception("移動檔案失敗");
}
return $this->savePath;
}
public function makeThumb($maxW = 100, $maxH = 100) {
if (!$this->savePath) throw new Exception("請先上傳");
list($w, $h, $type) = getimagesize($this->savePath);
$ratio = min($maxW/$w, $maxH/$h);
$nw = (int)($w*$ratio); $nh = (int)($h*$ratio);
$thumb = imagecreatetruecolor($nw, $nh);
$src = $this->createSource($this->savePath, $type);
imagecopyresampled($thumb, $src, 0,0,0,0, $nw,$nh, $w,$h);
$out = $this->insertSuffix($this->savePath, '_thumb');
$this->outputImage($thumb, $out, $type);
imagedestroy($src); imagedestroy($thumb);
return $out;
}
// 內部方法:checkError, checkMime, checkExt, checkSize, checkUpload, ensureDir, randName, insertSuffix, createSource, outputImage
// (完整代碼見上一篇「PHP 圖片上傳類實現」一文,此處省略重複)
}
upload();
$thumb = $uploader->makeThumb(150, 150);
echo "上傳成功!
";
echo "原圖:
";
echo "縮略圖:
";
} catch (Exception $e) {
echo "錯誤:{$e->getMessage()}
";
}
}
?>
md5(uniqid(microtime(true), true)) 幾乎零碰撞。imagecopyresampled 高品質重採樣。name="files[]" 迴圈處理)。