File size: 1,625 Bytes
57cab59
 
 
 
fe7c659
 
57cab59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
819bacd
 
 
 
 
 
 
 
 
 
 
57cab59
 
 
 
 
 
 
 
 
819bacd
 
 
 
57cab59
819bacd
57cab59
 
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import os
from typing import Dict

from fastapi import UploadFile
from app.db_local_storage.files_db import FILES_DIRECTORY, FILES_NAMES_DATABASE
from app.db_local_storage.documents_db import documents_db


class UploadDocumentFeature:

    @staticmethod
    def ensure_directory_exists(folder_path: str) -> None:
        """Ensure that the directory exists."""
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)

    @staticmethod
    async def saveFile(document: UploadFile, directory: str) -> str:
        """Save the uploaded file to the specified directory."""
        file_path = os.path.join(directory, document.filename)
        with open(file_path, "wb") as file:
            content = await document.read()
            file.write(content)
        return file

    @staticmethod
    async def SaveFileMemory(document: UploadFile) -> str:
        """Save the uploaded file to memory."""
        UploadDocumentFeature.ensure_directory_exists(FILES_DIRECTORY)
        id = len(FILES_NAMES_DATABASE) + 1
        FILES_NAMES_DATABASE[id] = document.filename

        file = await UploadDocumentFeature.saveFile(document, FILES_DIRECTORY)
        return file

    @staticmethod
    async def uploadFile(document: UploadFile) -> Dict[str, str]:
        """
        Upload a file to the server
        :param document: the file to upload
        :return: a message to confirm the upload
        """

        data = {
            "id": len(documents_db) + 1,
            "filename": document.filename,
        }

        documents_db.append(data)

        return {"message": "Document Updated"}