File size: 1,205 Bytes
e1fb2f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import os
from fastapi import APIRouter, HTTPException, UploadFile
from fastapi.responses import JSONResponse

from src.utils import logger

from src.services import FileService

import aiofiles

class FileController:
    def __init__(self):
        self.file_service = FileService
        self.router = APIRouter(prefix="/upload_file", tags=["file_upload"])
        self.router.add_api_route("/", self.upload_file, methods=["POST"])

    async def upload_file(self, file: UploadFile):
        try:
            async with aiofiles.tempfile.TemporaryDirectory() as temp_dir:
                temp_file_path = os.path.join(temp_dir, file.filename)
                async with aiofiles.open(temp_file_path, "wb") as f:
                    await f.write(file.file.read())
                async with self.file_service() as file_service:
                    response = await file_service.upload_file(temp_file_path)
            return JSONResponse(
                {
                    "status": "success",
                    "data": {"web_url": response},
                }
            )
        except Exception as e:
            logger.error(e)
            raise HTTPException(status_code=500, detail=str(e))