You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI部署App Engine时突破35MB文件上传限制方案咨询

解决App Engine上FastAPI大文件上传限制的方案

要绕开App Engine 35MB的POST请求限制,同时保留预处理和数据库记录的逻辑,最佳方案是让客户端通过签名URL直接上传文件到GCS,而FastAPI只负责预处理校验、创建数据库记录并生成签名URL。具体步骤如下:

1. 修改FastAPI上传接口逻辑

不再直接接收完整文件,而是先处理表单中的元数据(文件名、类型、自定义名称),完成校验和数据库记录创建后,返回一个GCS签名URL给客户端,让客户端直接向GCS上传文件。

示例代码:

from datetime import timedelta
@router.post('/upload-init')
def upload_init(
    name: str = Form(...),
    filename: str = Form(...),
    content_type: str = Form(...),
    db=Depends(get_session)
):
    # 校验文件类型
    if not content_type.startswith('video/'):
        error = "File must be a video"
        return RedirectResponse(url='/files?error_message=' + error, status_code=302)
    
    # 创建数据库记录(可先标记为"待上传",后续根据需要更新状态)
    db_record = create_db_record(db, name, filename, content_type)
    db.commit()

    # 生成GCS签名URL
    storage_client = storage.Client.from_service_account_json('service_account.json')
    bucket = storage_client.get_bucket('myapp.appspot.com')
    blob = bucket.blob(filename)
    
    # 设置签名URL过期时间(示例为30分钟),权限为写入
    signed_url = blob.generate_signed_url(
        version="v4",
        expiration=timedelta(minutes=30),
        method="PUT",
        content_type=content_type
    )

    # 返回签名URL给客户端,前端用此URL直接上传文件
    return {"signed_url": signed_url, "redirect_url": "/"}

2. 前端调整上传流程

前端需要先调用/upload-init接口获取签名URL,再通过PUT请求将文件直接上传到该URL。示例JS代码:

async function uploadFile(formData) {
    // 第一步:获取签名URL
    const initForm = new URLSearchParams();
    initForm.append('name', formData.get('name'));
    initForm.append('filename', formData.get('file').name);
    initForm.append('content_type', formData.get('file').type);

    const initResponse = await fetch('/upload-init', {
        method: 'POST',
        body: initForm
    });
    const { signed_url, redirect_url } = await initResponse.json();

    // 第二步:直接上传文件到GCS
    await fetch(signed_url, {
        method: 'PUT',
        body: formData.get('file'),
        headers: {
            'Content-Type': formData.get('file').type
        }
    });

    // 上传完成后跳转
    window.location.href = redirect_url;
}

3. 可选:GCS上传完成后的后续处理

如果文件上传完成后需要FastAPI执行额外逻辑(比如更新数据库状态、视频转码等),可以配置GCS的Cloud Pub/Sub通知:

  • 给目标GCS Bucket配置通知规则,当有文件上传成功时,发送事件消息到指定Pub/Sub主题
  • 在FastAPI中实现一个订阅接口,监听该Pub/Sub主题,接收上传完成事件后执行后续处理

方案优势

  • 客户端直接与GCS通信,完全绕过App Engine的POST大小限制,支持任意大文件上传
  • FastAPI仅处理轻量元数据,不会触发GFE的413错误
  • 完整保留了文件类型校验、数据库记录创建的核心业务逻辑

内容的提问来源于stack exchange,提问作者MattKA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 07:05:26