-
Notifications
You must be signed in to change notification settings - Fork 114
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: support download uploaded documents (#532)
part of #466 --------- Co-authored-by: MingWei Liu <[email protected]>
- Loading branch information
1 parent
9b05f10
commit aaf81b9
Showing
2 changed files
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
from fastapi import FastAPI, HTTPException, APIRouter | ||
from fastapi.responses import StreamingResponse | ||
from sqlmodel import Session | ||
from app.api.deps import SessionDep | ||
from app.repositories import document_repo | ||
from app.file_storage import get_file_storage | ||
|
||
router = APIRouter() | ||
|
||
@router.get("/documents/{doc_id}/download") | ||
def download_file( | ||
doc_id: int, | ||
session: SessionDep | ||
): | ||
doc = document_repo.must_get(session, doc_id) | ||
|
||
name = doc.source_uri | ||
filestorage = get_file_storage() | ||
if filestorage.exists(name): | ||
file_size = filestorage.size(name) | ||
headers = {"Content-Length": str(file_size)} | ||
def iterfile(): | ||
with filestorage.open(name) as f: | ||
yield from f | ||
return StreamingResponse( | ||
iterfile(), | ||
media_type = doc.mime_type, | ||
headers = headers | ||
) | ||
else: | ||
raise HTTPException(status_code = 404, detail = "File not found") | ||
|
||
|
||
|