feat: add delete file feature

main
MrWaradana 2 months ago
parent 2700034646
commit 45198cb50e

@ -136,6 +136,27 @@ async def delete_uploaded_file(db_session: DbSession, uploaded_file_id: str):
detail=[{"msg": "A data with this id does not exist."}],
)
# Attempt to delete the file on disk if a file_url is present
file_url = getattr(uploaded_file, "file_url", None)
if file_url:
try:
# file_url is stored like "/uploads/<timestamp>/<filename>"
src_dir = Path(__file__).resolve().parent.parent
file_path = src_dir / Path(file_url.lstrip("/"))
if file_path.exists():
file_path.unlink()
# try to remove the timestamp directory if it's empty
try:
file_path.parent.rmdir()
except OSError:
# not empty or cannot remove, ignore
pass
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to delete file from disk: {str(e)}",
)
await delete(db_session=db_session, uploaded_file_id=uploaded_file_id)
return StandardResponse(message="Data deleted successfully", data=uploaded_file)

Loading…
Cancel
Save