61 lines
1.9 KiB
Python
61 lines
1.9 KiB
Python
|
import os
|
||
|
import uuid
|
||
|
import tempfile
|
||
|
import fastapi
|
||
|
from fastapi import HTTPException
|
||
|
import logging
|
||
|
|
||
|
from Config.Config import ALY_OSS_PREFIX
|
||
|
from Util import OssUtil
|
||
|
|
||
|
# 配置日志
|
||
|
logger = logging.getLogger(__name__)
|
||
|
|
||
|
|
||
|
# 创建APIRouter
|
||
|
router = fastapi.APIRouter()
|
||
|
|
||
|
@router.post("/api/upload_oss")
|
||
|
async def upload_oss(request: fastapi.Request):
|
||
|
# 获取上传的文件
|
||
|
try:
|
||
|
form = await request.form()
|
||
|
file = form.get("file")
|
||
|
if not file:
|
||
|
raise HTTPException(status_code=400, detail="未上传文件")
|
||
|
|
||
|
# 检查文件格式
|
||
|
filename = file.filename
|
||
|
if not filename.lower().endswith((".jpg", ".jpeg", ".png")):
|
||
|
raise HTTPException(status_code=400, detail="只支持jpg、jpeg、png格式的图片")
|
||
|
|
||
|
# 生成UUID和新的文件名
|
||
|
file_ext = os.path.splitext(filename)[1].lower()
|
||
|
new_filename = f"{uuid.uuid4()}{file_ext}"
|
||
|
|
||
|
# 构建OSS对象名称
|
||
|
object_name = f"{ALY_OSS_PREFIX}/{new_filename}"
|
||
|
|
||
|
# 保存临时文件并上传
|
||
|
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
||
|
temp_file.write(await file.read())
|
||
|
temp_file_path = temp_file.name
|
||
|
|
||
|
# 调用OssUtil上传文件
|
||
|
upload_success = OssUtil.upload_to_oss(temp_file_path, object_name)
|
||
|
|
||
|
# 删除临时文件
|
||
|
os.unlink(temp_file_path)
|
||
|
|
||
|
if upload_success:
|
||
|
# 获取文件URL
|
||
|
file_url = OssUtil.get_url(new_filename)
|
||
|
return {"code": 0, "msg": "上传成功", "data": {"url": file_url, "filename": new_filename}}
|
||
|
else:
|
||
|
raise HTTPException(status_code=500, detail="文件上传失败")
|
||
|
|
||
|
except HTTPException:
|
||
|
raise
|
||
|
except Exception as e:
|
||
|
logger.error(f"文件上传异常: {str(e)}")
|
||
|
raise HTTPException(status_code=500, detail=f"上传异常: {str(e)}")
|