Skip to content

Commit

Permalink
👀 preview any file type
Browse files Browse the repository at this point in the history
  • Loading branch information
jiisanda committed Dec 10, 2023
1 parent d6eb662 commit 9094c7f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
6 changes: 5 additions & 1 deletion api/routes/documents/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
15 changes: 13 additions & 2 deletions db/repositories/documents/documents.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os.path
import tempfile
from typing import Any, Dict, List
import boto3
Expand Down Expand Up @@ -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)

0 comments on commit 9094c7f

Please sign in to comment.