Skip to content

Instantly share code, notes, and snippets.

@Ichinga-Samuel
Last active November 1, 2025 12:16
Show Gist options
  • Select an option

  • Save Ichinga-Samuel/c4b215d6cd9801682fdb7fde87317e38 to your computer and use it in GitHub Desktop.

Select an option

Save Ichinga-Samuel/c4b215d6cd9801682fdb7fde87317e38 to your computer and use it in GitHub Desktop.
import asyncio
from logging import getLogger
from .main import FileUpload, FileData, Path
from fastapi import UploadFile
logger = getLogger()
class Local(FileUpload):
"""
Local storage for FastAPI.
"""
async def upload(self, *, file: UploadFile) -> FileData:
"""
Upload a file to the destination.
Args:
file UploadFile: File to upload
Returns:
FileData: Result of file upload
"""
try:
dest = self.config.get('dest') or Path('uploads') / f'{file.filename}'
file_object = await file.read()
with open(f'{dest}', 'wb') as fh:
fh.write(file_object)
await file.close()
return FileData(path=dest, message=f'{file.filename} saved successfully', content_type=file.content_type,
size=file.size, filename=file.filename)
except Exception as err:
logger.error(f'Error uploading file: {err} in {self.__class__.__name__}')
return FileData(status=False, error=str(err), message=f'Unable to save file')
async def multi_upload(self, *, files: list[UploadFile]) -> list[FileData]:
"""
Upload multiple files to the destination.
Args:
files (list[tuple[str, UploadFile]]): A list of tuples of field name and the file to upload.
Returns:
list[FileData]: A list of uploaded file data
"""
res = await asyncio.gather(*[self.upload(file=file) for file in files])
return list(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment