From 9094c7feae9cff735faad891b554b867be244265 Mon Sep 17 00:00:00 2001 From: jiisanda Date: Sun, 10 Dec 2023 17:42:30 +0530 Subject: [PATCH] =?UTF-8?q?=F0=9F=91=80=20preview=20any=20file=20type?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/routes/documents/document.py | 6 +++++- db/repositories/documents/documents.py | 15 +++++++++++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/api/routes/documents/document.py b/api/routes/documents/document.py index 9808b23..eeedd2d 100644 --- a/api/routes/documents/document.py +++ b/api/routes/documents/document.py @@ -211,7 +211,11 @@ async def get_document_preview( try: get_document_metadata = dict(await metadata_repository.get(document=document, owner=user)) return await repository.preview(document=get_document_metadata) - except Exception as e: + except TypeError as e: raise HTTP_404( msg="Document does not exists." ) from e + except ValueError as e: + raise HTTP_400( + msg="File type is not supported for preview" + ) diff --git a/db/repositories/documents/documents.py b/db/repositories/documents/documents.py index 863d902..42ae8ac 100644 --- a/db/repositories/documents/documents.py +++ b/db/repositories/documents/documents.py @@ -1,3 +1,4 @@ +import os.path import tempfile from typing import Any, Dict, List import boto3 @@ -199,8 +200,18 @@ async def preview(self, document: Dict[str, Any]) -> FileResponse: s3_object = self.client.get_object(Bucket=settings.s3_bucket, Key=key) file = s3_object['Body'].read() - with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp: + # Determining the file extension from the key and media type for File Response + _, extension = os.path.splitext(key) + if extension.lower() in ['.jpg', '.jpeg', '.png', '.gif']: + media_type = 'image/' + extension.lower().lstrip('.') + elif extension.lower() == '.pdf': + media_type = 'application/pdf' + else: + raise ValueError("Unsupported file type.") + + # Creating a temp file + with tempfile.NamedTemporaryFile(delete=False, suffix=extension) as temp: temp.write(file) temp_path = temp.name - return FileResponse(temp_path, media_type='application/pdf') + return FileResponse(temp_path, media_type=media_type)