Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support download uploaded documents #532

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
2 changes: 2 additions & 0 deletions backend/app/api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
user,
api_key,
feedback,
document,
)
from app.api.admin_routes.knowledge_base.routes import (
router as admin_knowledge_base_router,
Expand Down Expand Up @@ -52,6 +53,7 @@
api_router.include_router(feedback.router, tags=["chat"])
api_router.include_router(user.router, tags=["user"])
api_router.include_router(api_key.router, tags=["auth"])
api_router.include_router(document.router, tags=["documents"])
api_router.include_router(admin_chat_engine.router, tags=["admin/chat_engine"])
api_router.include_router(admin_document_router, tags=["admin/documents"])
api_router.include_router(admin_feedback.router, tags=["admin/feedback"])
Expand Down
35 changes: 35 additions & 0 deletions backend/app/api/routes/document.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
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:
while chunk := f.read(8192): # 每次读取 8KB
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please refer to FastAPI Document. It's not necessary to manually call f.read().

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

yield chunk
return StreamingResponse(
iterfile(),
media_type = doc.mime_type,
headers = headers
)
else:
raise HTTPException(status_code = 404, detail = "File not found")