[英]How to return a PDF file from in-memory buffer using FastAPI?
我想從 s3 獲取一個 PDF 文件,然后從 FastAPI 后端返回到前端。
這是我的代碼:
@router.post("/pdf_document")
def get_pdf(document : PDFRequest) :
s3 = boto3.client('s3')
file=document.name
f=io.BytesIO()
s3.download_fileobj('adm2yearsdatapdf', file,f)
return StreamingResponse(f, media_type="application/pdf")
這個 API 返回200
狀態碼,但它不返回 PDF 文件作為響應。
由於整個文件數據已經加載到 memory 中,因此使用StreamingResponse
幾乎沒有意義。 您應該使用Response
,通過傳遞文件字節(使用BytesIO.getvalue()
獲取包含緩沖區全部內容的字節),定義media_type
,以及設置Content-Disposition
header,以便文件可以可以在瀏覽器中查看或下載到用戶的設備。 有關更多詳細信息,請查看this以及this和this answer。
from fastapi import Response
@app.get("/pdf")
def get_pdf():
...
buffer = io.BytesIO()
...
headers = {'Content-Disposition': 'attachment; filename="out.pdf"'}
return Response(buffer.getvalue(), headers=headers, media_type='application/pdf')
要在瀏覽器中查看而不是下載 PDF 文件,請使用:
headers = {'Content-Disposition': 'inline; filename="out.pdf"'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.