SAE (Sina App Engine) 代碼層唯讀,持久化檔案必須使用 **Storage 服務**(分布式對象存儲)。本文示範原生 `saestor://` 協議流式上傳、目錄自動建立、權限控制、遷移本地上傳代碼的最小改動。
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<button type="submit">上傳</button>
</form>
<?php
$domain = 'myapp-assets'; // SAE 控制台建立的域名
$uploadDir = "saestor://{$domain}/uploads/" . date('Y/m/d/');
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
$file = $_FILES['file'];
if ($file['error'] !== UPLOAD_ERR_OK) {
die('Upload error: ' . $file['error']);
}
$dest = $uploadDir . basename($file['name']);
// 直接移動臨時檔到 Storage,流式寫入,不佔用本地磁碟
if (move_uploaded_file($file['tmp_name'], $dest)) {
echo "上傳成功:{$dest}";
} else {
echo "上傳失敗";
}
}
?>
<?php
$src = fopen('php://input', 'rb'); // 或 fopen($_FILES['file']['tmp_name'], 'rb')
$dest = fopen("saestor://{$domain}/large/{$filename}", 'wb');
stream_copy_to_stream($src, $dest); // 內核級零拷貝
fclose($src);
fclose($dest);
?>
<?php
class SaeStorage
{
private string $domain;
public function __construct(string $domain) { $this->domain = $domain; }
private function path(string $relative): string
{
return "saestor://{$this->domain}/" . ltrim($relative, '/');
}
public function write(string $path, string $content): bool
{
return file_put_contents($this->path($path), $content) !== false;
}
public function read(string $path): string|false
{
return file_get_contents($this->path($path));
}
public function delete(string $path): bool
{
return @unlink($this->path($path));
}
public function exists(string $path): bool
{
return file_exists($this->path($path));
}
public function listDir(string $dir): array
{
$dh = @opendir($this->path($dir));
if (!$dh) return [];
$files = [];
while (($f = readdir($dh)) !== false) {
if ($f !== '.' && $f !== '..') $files[] = $f;
}
closedir($dh);
return $files;
}
public function getUrl(string $path): string
{
// 公開讀取域可直接拼接 CDN 域名
return "https://{$this->domain}.stor.sinaapp.com/" . ltrim($path, '/');
}
}
?>
| 本地代碼 | SAE 修改 |
|---|---|
| `move_uploaded_file($tmp, $localPath)` | `move_uploaded_file($tmp, "saestor://{$domain}/{$path}")` |
| `file_put_contents($localPath, $data)` | `file_put_contents("saestor://{$domain}/{$path}", $data)` |
| `fopen($localPath, 'r')` | `fopen("saestor://{$domain}/{$path}", 'r')` |
| `unlink($localPath)` | `unlink("saestor://{$domain}/{$path}")` |
| `is_dir($localPath)` / `mkdir($localPath)` | 同樣支援 `saestor://`,**mkdir 通常可省略** |
| 圖片處理 `imagecreatefromjpeg($localPath)` | **不支援** GD 直接讀取,需先 `file_get_contents` 到字串或暫存本地處理後再存回 |
掌握 `saestor://` 協議,本地代碼幾乎零改動即可無縫遷移至 SAE 分布式存儲,享受無限擴容、高可用、CDN 加速。