refactor(third_party_api): 重构第三方API模块结构和逻辑 feat(third_party_api): 新增OCR图片识别接口 style(third_party_api): 优化API请求参数和响应模型 build: 添加静态文件目录挂载配置
51 lines
1.5 KiB
Python
51 lines
1.5 KiB
Python
import os
|
|
from pathlib import Path
|
|
from typing import List
|
|
from fastapi import UploadFile
|
|
from app.schemas.upload import ImageUploadResponse
|
|
|
|
class UploadController:
|
|
"""文件上传控制器"""
|
|
|
|
@staticmethod
|
|
async def upload_image(file: UploadFile) -> ImageUploadResponse:
|
|
"""
|
|
上传图片
|
|
:param file: 上传的图片文件
|
|
:return: 图片URL和文件名
|
|
"""
|
|
# 检查文件类型
|
|
if not file.content_type.startswith('image/'):
|
|
raise ValueError("只支持上传图片文件")
|
|
|
|
# 获取项目根目录
|
|
base_dir = Path(__file__).resolve().parent.parent
|
|
# 图片保存目录
|
|
upload_dir = base_dir / "static" / "images"
|
|
|
|
# 确保目录存在
|
|
if not upload_dir.exists():
|
|
upload_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
# 生成文件名
|
|
filename = file.filename
|
|
file_path = upload_dir / filename
|
|
|
|
# 如果文件已存在,重命名
|
|
counter = 1
|
|
while file_path.exists():
|
|
name, ext = os.path.splitext(filename)
|
|
filename = f"{name}_{counter}{ext}"
|
|
file_path = upload_dir / filename
|
|
counter += 1
|
|
|
|
# 保存文件
|
|
content = await file.read()
|
|
with open(file_path, "wb") as f:
|
|
f.write(content)
|
|
|
|
# 返回文件URL
|
|
return ImageUploadResponse(
|
|
url=f"/static/images/{filename}",
|
|
filename=filename
|
|
) |