保定ai问答主体项目
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

74 lines
2.0 KiB

# app/api/v1/upload/upload.py
import os
import uuid
from fastapi import APIRouter, File, UploadFile
from fastapi.responses import JSONResponse
from app.settings.config import settings
router = APIRouter()
# 文件存储根目录
UPLOAD_DIR = os.path.join(settings.BASE_DIR, 'web', 'public', 'resource')
@router.post('/image', summary='上传图片')
async def upload_image(file: UploadFile = File(...)):
try:
# 确保目录存在
os.makedirs(os.path.join(UPLOAD_DIR, 'images'), exist_ok=True)
# 生成唯一文件名
filename = f'{uuid.uuid4()}_{file.filename}'
file_path = os.path.join(UPLOAD_DIR, 'images', filename)
# 保存文件
with open(file_path, 'wb') as f:
f.write(await file.read())
# 构建访问URL
file_url = f'/resource/images/{filename}'
return JSONResponse({
'errno': 0,
'data': [{
'url': file_url,
'alt': '',
'href': ''
}]
})
except Exception as e:
return JSONResponse({
'errno': 1,
'message': str(e)
})
@router.post('/video', summary='上传视频')
async def upload_video(file: UploadFile = File(...)):
try:
# 确保目录存在
os.makedirs(os.path.join(UPLOAD_DIR, 'videos'), exist_ok=True)
# 生成唯一文件名
filename = f'{uuid.uuid4()}_{file.filename}'
file_path = os.path.join(UPLOAD_DIR, 'videos', filename)
# 保存文件
with open(file_path, 'wb') as f:
f.write(await file.read())
# 构建访问URL
file_url = f'/resource/videos/{filename}'
return JSONResponse({
'errno': 0,
'data': {
'url': file_url,
'duration': 0 # 实际应用中可以计算视频时长
}
})
except Exception as e:
return JSONResponse({
'errno': 1,
'message': str(e)
})