萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

SAE Storage 服務使用指南:PHP 直寫分布式存儲、上傳、目錄自動建立

SAE (Sina App Engine) 代碼層唯讀,持久化檔案必須使用 **Storage 服務**(分布式對象存儲)。本文示範原生 `saestor://` 協議流式上傳、目錄自動建立、權限控制、遷移本地上傳代碼的最小改動。

核心概念

  • Domain(域):頂層命名空間,對應 SAE 控制台建立的 Storage 域(如 `assets`、`avatars`)。
  • 路徑格式:`saestor:///`,標準 PHP 檔案函式(`fopen`、`file_put_contents`、`move_uploaded_file`、`mkdir`、`is_dir`、`unlink`)均支援。
  • 自動建立目錄:寫入檔案時中間目錄自動創建,**無需手動 `mkdir`**。

最小改動:HTML 表單 + PHP 接收直存 Storage

<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` 到字串或暫存本地處理後再存回

權限與安全

  • Domain 可設為**私有**(需簽名 URL 下載)或**公開**(直連 CDN)。
  • 上傳前驗證 MIME、尺寸、副檔名,防惡意檔案污染 Domain。
  • 敏感檔案(身份證、合同)務必用私有 Domain + 簽名 URL 限時下載。

掌握 `saestor://` 協議,本地代碼幾乎零改動即可無縫遷移至 SAE 分布式存儲,享受無限擴容、高可用、CDN 加速。

copyright © 萬盛學電腦網 all rights reserved