廣告位招商中 歡迎洽談

如何在 Replit 部署中使用 Replit Object Storage 持久化使用者上傳檔案

Sergio García Encina · 365Finds Editorial
已收錄 88,650 篇 Wiki 文章

讓你的 AI 用上 365 Wiki

複製下方的提示詞,貼給你常用的 AI,然後直接提問。

下載完整版 Skill

先用提示詞體驗;經常使用時,安裝完整版 365Wiki Skill,以後無需重複複製。沒有常用 AI?Gemini、Microsoft Copilot 等網頁版也可以。

365Wiki Skill

全端開發者在將應用程式從 Replit 工作區推向生產環境部署(Deployments)時,經常會遭遇一個猝不及防的重大故障:使用者上傳的大頭貼、文件附件或系統動態產生的報告,在發布新版本後徹底消失。在工作區開發時,程式碼將檔案寫入 ./uploads/ 看似運作順暢,檔案靜靜存放在目錄樹中,即便手動修改程式碼也能即刻存取。然而一旦透過 Replit Deployments 發布到線上環境——無論選擇 Autoscale(自動彈性擴縮)還是 Reserved VM(專屬虛擬機)——底層的基礎設施結構產生了本質上的劇變。

在 365Finds 看來,將使用者上傳的二進位檔案直接寫入本地容器磁碟,是 Replit 全端開發中最具破壞力的反模式(Anti-pattern)。Replit 的生產部署運作於完全無狀態、暫時性的容器環境中。每當應用程式因閒置縮容至零、程序崩潰重啟,或是因程式碼更新而觸發重新構建,當前運作中的容器檔案系統就會被徹底銷毀,並從專案儲存庫的構建產物中重新初始化。更甚者,在多執行個體的水平擴展架構下,上傳至執行個體 A 的檔案絕不會同步出現在執行個體 B 的本地磁碟中。

要讓使用者上傳檔案在跨版本部署與容器重構中真正持久化,必須將二進位非結構化資料與容器運算環境完全解耦。Replit 原生提供的全託管解決方案即為 Replit Object Storage(在使用者介面中亦標示為 App Storage)。本文將深入剖析其運作原理、配置步驟,以及在 Node.js 與 Python 環境下的完整實作指南。


為何本地檔案系統在生產部署中必然失效

理解 Replit 部署架構的生命週期,就能明白依賴本地磁碟為何必定失敗:

  1. 短暫容器特性(Ephemeral Containers): 線上部署隔離於容器沙箱內。任何在運行期間由程式寫入磁碟的檔案,皆無法在容器重啟時保留。
  2. 無狀態自動擴縮容: Autoscale 機制會依即時流量動態啟動或凍結容器執行個體。兩個相鄰發出的請求可能被路由至完全不同的虛擬節點,彼此擁有完全獨立的檔案系統。
  3. 構建期與執行期分離: 部署進行時,Replit 會將工作區專案檔案凍結為不可變的映像檔。伺服器對外提供服務時所產生的新檔案,僅存在於執行個體的暫時可寫層。

Replit Object Storage 從架構層面解決了這個瓶頸。其底層直接由 Google Cloud Storage 支援,提供獨立於運算容器的持久化雲端物件儲存庫(Bucket),無論是開發工作區還是線上多個部署副本,皆能安全並行存取。

[ 使用者瀏覽器 ]
       |
       |  1. 上傳請求(Multipart Form)
       v
[ Replit 部署執行個體 ](無狀態暫時性容器)
       |
       |  2. 串流位元組 / 記憶體 Buffer
       v
[ Replit Object Storage ](雲端持久化儲存庫)
       ^
       |  3. 關聯中繼資料(Key、MIME、大小、使用者 ID)
[ Replit PostgreSQL ](關聯式資料庫)

步驟一:啟用與配置 Replit Object Storage

相較於自建或串接外部公有雲儲存服務,Replit Object Storage 最大優勢在於免除了複雜的 IAM 身分驗證、服務帳戶金鑰(JSON Key)與手動設定環境變數的負擔。存取憑證與端點已由系統自動注入至工作區與線上部署容器內。

  1. 在 Replit 工作區中開啟專案。
  2. 展開左側側邊欄的 Tools 工具箱。
  3. 找到並點選 App Storage(或 Object Storage)。
  4. 點選 Create Bucket(或初始化預設儲存庫)。Replit 會自動建立並綁定該專案專屬的雲端儲存空間。
  5. 確認預設配置。官方 SDK 在不帶參數初始化時會自動連接該預設儲存庫,無需手動於 Secrets 中填入連線金鑰。

步驟二:Node.js / TypeScript 程式碼實作

在 Node.js 與 TypeScript 環境中,官方提供 @replit/object-storage 套件。

在終端機中安裝所需套件:

npm install @replit/object-storage multer uuid
npm install --save-dev @types/multer @types/uuid

檔案上傳中介軟體的關鍵設計

切勿使用 multer.diskStorage() 將檔案暫存於本機 ./uploads。伺服器若意外中斷將產生無人清理的孤立暫存檔,且白白佔用磁碟配額。365Finds 強烈建議採用記憶體儲存模式(multer.memoryStorage()),在記憶體中緩衝檔案後,直接串流寫入 Replit Object Storage。

伺服器端實作(Express.js)

import express, { Request, Response } from "express";
import multer from "multer";
import { v4 as uuidv4 } from "uuid";
import path from "path";
import { Client } from "@replit/object-storage";

const app = express();
const client = new Client(); // 自動解析環境憑據並連線預設儲存庫

// 設定 Multer 記憶體暫存與檔案大小限制(例如 10 MB)
const upload = multer({
  storage: multer.memoryStorage(),
  limits: {
    fileSize: 10 * 1024 * 1024,
  },
});

// 檔案上傳端點
app.post("/api/upload", upload.single("file"), async (req: Request, res: Response) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: "未接收到上傳檔案。" });
    }

    // 產生防碰撞的唯一識別檔名
    const ext = path.extname(req.file.originalname);
    const storageKey = `uploads/${uuidv4()}${ext}`;

    // 將記憶體 Buffer 直接寫入物件儲存庫
    const uploadResult = await client.uploadFromBytes(storageKey, req.file.buffer);

    if (!uploadResult.ok) {
      console.error("物件儲存寫入失敗:", uploadResult.error);
      return res.status(500).json({ error: "檔案持久化失敗。" });
    }

    // 回傳儲存識別路徑,供寫入 PostgreSQL 資料庫記錄
    return res.status(201).json({
      success: true,
      storageKey,
      originalName: req.file.originalname,
      mimeType: req.file.mimetype,
      size: req.file.size,
    });
  } catch (error) {
    console.error("上傳處理發生例外:", error);
    return res.status(500).json({ error: "內部伺服器錯誤。" });
  }
});

// 檔案下載與串流端點
app.get("/api/files/:key(*)", async (req: Request, res: Response) => {
  try {
    const storageKey = req.params.key;

    // 從物件儲存庫取得位元組資料
    const downloadResult = await client.downloadAsBytes(storageKey);

    if (!downloadResult.ok) {
      return res.status(404).json({ error: "找不到指定的檔案。" });
    }

    const buffer = Buffer.from(downloadResult.value);

    // 設定快取標頭與輸出
    res.setHeader("Cache-Control", "private, max-age=86400");
    return res.send(buffer);
  } catch (error) {
    console.error("下載讀取失敗:", error);
    return res.status(500).json({ error: "無法取得該檔案。" });
  }
});

// 檔案刪除端點
app.delete("/api/files/:key(*)", async (req: Request, res: Response) => {
  try {
    const storageKey = req.params.key;
    const deleteResult = await client.delete(storageKey);

    if (!deleteResult.ok) {
      return res.status(404).json({ error: "檔案不存在或早已被刪除。" });
    }

    return res.status(200).json({ success: true, message: "檔案已自雲端徹底刪除。" });
  } catch (error) {
    console.error("刪除失敗:", error);
    return res.status(500).json({ error: "無法執行檔案刪除。" });
  }
});

export default app;

步驟三:Python 程式碼實作

若後端選用 Python 生態系(如 FastAPI 或 Flask),Replit 官方維護了 replit-object-storage 套件。

安裝依賴:

pip install replit-object-storage fastapi python-multipart uvicorn

伺服器端實作(FastAPI)

import uuid
import os
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import Response
from replit.object_storage import Client

app = FastAPI()
client = Client()

@app.post("/api/upload")
async def upload_file(file: UploadFile = File(...)):
    # 讀取檔案二進位位元組
    content = await file.read()
    
    if len(content) > 10 * 1024 * 1024:
        raise HTTPException(status_code=400, detail="檔案超出 10MB 上限。")

    ext = os.path.splitext(file.filename)[1]
    storage_key = f"uploads/{uuid.uuid4()}{ext}"

    try:
        # 直接上傳至 Replit Object Storage
        client.upload_from_bytes(storage_key, content)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"儲存上傳失敗: {str(e)}")

    return {
        "status": "success",
        "storage_key": storage_key,
        "filename": file.filename,
        "content_type": file.content_type,
        "size_bytes": len(content),
    }

@app.get("/api/files/{storage_key:path}")
def get_file(storage_key: str):
    try:
        data = client.download_as_bytes(storage_key)
        return Response(content=data, media_type="application/octet-stream")
    except Exception:
        raise HTTPException(status_code=404, detail="檔案不存在。")

@app.delete("/api/files/{storage_key:path}")
def delete_file(storage_key: str):
    try:
        client.delete(storage_key)
        return {"status": "success", "message": "檔案已刪除。"}
    except Exception:
        raise HTTPException(status_code=404, detail="無法刪除檔案。")

生產架構實踐:大型 Blob 與結構化資料分離

新手常犯的致命誤區,是直接把物件儲存庫當成關聯式資料庫查詢。使用 client.list() 去迴圈過濾特定使用者的上傳記錄,會隨著檔案數累積導致延遲直線攀升。

365Finds 堅持的架構準則是將檔案二進位內容與關聯資料在庫中嚴格拆分:

功能層面承載平台記錄之關鍵欄位
二進位檔案本體Replit Object Storage原始二進位位元組、儲存鍵值(uploads/<uuid>.<ext>)
結構化中繼資料PostgreSQL 資料庫主鍵(UUID)、user_id、原始檔名、MIME 格式、檔案大小、建立時間戳記

查詢使用者歷史檔案列表時,只需在 PostgreSQL 中執行毫秒級的 SQL 查詢;僅當使用者真正點擊檢視或下載時,再憑藉 storage_key 前往 Replit Object Storage 提取實體資料。


365Finds 的選型取捨評估

衡量任何雲端儲存工具都需要兼顧實務效益:

核心優勢

現存限制與考量

在 Replit 平台內維護一個需要保存使用者上傳資料的線上專案時,Replit Object Storage 是最乾淨俐落、能杜絕檔案失蹤風險的必選方案。


參考資料