feat: 私有桶签名 URL 支持 + TOS 凭证配置
后端 oss.py 新增 generate_presigned_url (TOS V4 Query String Auth), upload.py 新增 GET /upload/sign-url 端点。前端 api.ts 添加 getSignedUrl 方法,新增 useSignedUrl hook 支持自动缓存和过期刷新。 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
2f24dcfd34
commit
58aed5f201
@@ -1,12 +1,12 @@
|
||||
"""
|
||||
文件上传 API
|
||||
"""
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
|
||||
from app.services.oss import generate_upload_policy, get_file_url
|
||||
from app.services.oss import generate_upload_policy, get_file_url, generate_presigned_url
|
||||
from app.config import settings
|
||||
from app.models.user import User
|
||||
from app.api.deps import get_current_user
|
||||
@@ -123,3 +123,48 @@ async def file_uploaded(
|
||||
file_size=request.file_size,
|
||||
file_type=request.file_type,
|
||||
)
|
||||
|
||||
|
||||
class SignedUrlResponse(BaseModel):
|
||||
"""签名 URL 响应"""
|
||||
signed_url: str
|
||||
expire_seconds: int
|
||||
|
||||
|
||||
@router.get("/sign-url", response_model=SignedUrlResponse)
|
||||
async def get_signed_url(
|
||||
url: str = Query(..., description="文件的原始 URL 或 file_key"),
|
||||
expire: int = Query(3600, ge=60, le=43200, description="有效期(秒),默认1小时,最长12小时"),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""
|
||||
获取私有桶文件的预签名访问 URL
|
||||
|
||||
前端在展示/下载文件前调用此接口,获取带签名的临时访问链接。
|
||||
支持传入完整 URL 或 file_key。
|
||||
"""
|
||||
from app.services.oss import parse_file_key_from_url
|
||||
|
||||
# 如果传入的是完整 URL,先解析出 file_key
|
||||
file_key = url
|
||||
if url.startswith("http"):
|
||||
file_key = parse_file_key_from_url(url)
|
||||
|
||||
if not file_key:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="无效的文件路径",
|
||||
)
|
||||
|
||||
try:
|
||||
signed_url = generate_presigned_url(file_key, expire_seconds=expire)
|
||||
except ValueError as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
|
||||
return SignedUrlResponse(
|
||||
signed_url=signed_url,
|
||||
expire_seconds=expire,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user