fix(image): 抠图结果下载后转存七牛云,解决前端 CORS 跨域加载失败

This commit is contained in:
小鱼开发
2026-05-23 09:50:40 +08:00
parent 222c468681
commit 6011225eec
+40 -4
View File
@@ -10,6 +10,7 @@ import logging
import uuid
from pathlib import Path
import httpx
from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile
from pydantic import BaseModel, Field
@@ -185,10 +186,45 @@ async def remove_background(
logger.info(f"[RemoveBackground] 抠图成功: {result.image_url[:80]}...")
return success_response(
data=RemoveBackgroundResponse(url=result.image_url),
message="抠图成功",
)
# 下载抠图结果并转存到七牛云(避免前端 CORS 问题)
try:
async with httpx.AsyncClient(timeout=60.0) as client:
img_resp = await client.get(result.image_url, follow_redirects=True)
img_resp.raise_for_status()
img_content = img_resp.content
if not img_content:
raise HTTPException(status_code=500, detail="抠图结果下载失败:内容为空")
# 上传到七牛云 image bucket
qiniu = get_qiniu_service()
bucket, domain = qiniu._get_bucket_and_domain("image")
unique_name = f"{uuid.uuid4().hex[:16]}.png"
file_key = qiniu.generate_key("image", unique_name)
stream = io.BytesIO(img_content)
upload_result = await qiniu.upload_stream_async(
stream=stream,
key=file_key,
mime_type="image/png",
bucket=bucket,
domain=domain,
)
qiniu_url = upload_result.get("url")
if not qiniu_url:
raise HTTPException(status_code=500, detail="抠图结果转存到七牛云失败")
logger.info(f"[RemoveBackground] 结果已转存七牛云: {qiniu_url[:80]}...")
return success_response(
data=RemoveBackgroundResponse(url=qiniu_url),
message="抠图成功",
)
except HTTPException:
raise
except Exception as e:
logger.error(f"[RemoveBackground] 结果转存失败: {e}")
raise HTTPException(status_code=500, detail=f"抠图结果转存失败: {e}")
except HTTPException:
raise