41 lines
950 B
Python
41 lines
950 B
Python
from fastapi import UploadFile, File, HTTPException
|
|
|
|
from config.rustfs import s3
|
|
from config.setting import settings
|
|
|
|
ALLOWED_IMAGE_TYPES = [
|
|
"image/jpeg",
|
|
"image/png",
|
|
"image/gif",
|
|
"image/webp",
|
|
"image/svg+xml",
|
|
]
|
|
|
|
BUCKET = 'blog'
|
|
NGINX_PROXY = 'rustfs'
|
|
|
|
|
|
async def upload_file(md5: str, file: UploadFile = File(...)) -> str:
|
|
# 校验文件类型是否是图片
|
|
if file.content_type not in ALLOWED_IMAGE_TYPES:
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail="只允许上传图片文件 (JPEG, PNG, GIF, WEBP, SVG)"
|
|
)
|
|
|
|
file_ext = file.filename.split('.')[-1]
|
|
unique_filename = f"{md5}.{file_ext}"
|
|
|
|
file_content = await file.read()
|
|
|
|
# 上传到S3
|
|
s3.put_object(
|
|
Bucket=BUCKET,
|
|
Key=unique_filename,
|
|
Body=file_content,
|
|
ContentType=file.content_type
|
|
)
|
|
|
|
# 返回文件url
|
|
return f"{NGINX_PROXY}/{BUCKET}/{unique_filename}"
|