45 lines
1.3 KiB
Python
45 lines
1.3 KiB
Python
import os
|
|
import uuid
|
|
from io import BytesIO
|
|
|
|
from PIL import Image
|
|
from fastapi import FastAPI, UploadFile
|
|
from fastapi.staticfiles import StaticFiles
|
|
|
|
|
|
def generate_uuid_from_file(file_content):
|
|
namespace_oid = uuid.UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8')
|
|
return uuid.uuid5(namespace_oid, str(file_content))
|
|
|
|
|
|
app = FastAPI(
|
|
prefix="/api",
|
|
tags=["Сервак для загрузки"],
|
|
)
|
|
|
|
app.mount("/static", StaticFiles(directory="static"), name="static")
|
|
|
|
|
|
@app.post('/upload_avatar', response_model=dict[str, str])
|
|
async def upload_avatar(file: UploadFile):
|
|
content = await file.read()
|
|
name = generate_uuid_from_file(content)
|
|
image = Image.open(BytesIO(content))
|
|
|
|
new_size = (512, 512)
|
|
resized_image = image.resize(new_size)
|
|
|
|
image_url = f"static/images/avatars/{name}_avatar.{image.format.lower()}"
|
|
resized_image.save(image_url)
|
|
return {"image_url": image_url}
|
|
|
|
|
|
@app.post("/upload_image", response_model=dict[str, str])
|
|
async def upload_image(file: UploadFile):
|
|
content = await file.read()
|
|
name = generate_uuid_from_file(content)
|
|
image = Image.open(BytesIO(content))
|
|
|
|
image_url = f"static/images/images/{name}_image.{image.format.lower()}"
|
|
image.save(image_url)
|
|
return {"image_url": image_url}
|