如何使用FastAPI返回和下载Excel文件?
如何使用FastAPI返回和下载Excel文件?
如何使用FastAPI返回Excel文件(版本:Office365)?文档看起来很简单。但是,我不知道要使用什么media_type
。这是我的代码:
import os from fastapi import FastAPI from fastapi.responses import FileResponse from pydantic import BaseModel from typing import Optional excel_file_path = r"C:\Users\some_path\the_excel_file.xlsx" app = FastAPI() class ExcelRequestInfo(BaseModel): client_id: str @app.post("/post_for_excel_file/") async def serve_excel(item: ExcelRequestInfo): # (Generate excel using item.) # For now, return a fixed excel. return FileResponse( path=excel_file_path, # Swagger UI says 'cannot render, look at console', but console shows nothing. media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' # Swagger renders funny chars with this argument: # 'application/vnd.ms-excel' )
假设我弄对了,如何下载文件?我可以使用由FastAPI生成的Swagger UI查看工作表吗?还是使用curl?理想情况下,我希望能够通过Excel下载和查看文件。
admin 更改状态以发布 2023年5月20日
您可以使用Content-Disposition
头部并使用attachment
参数来告诉浏览器该文件应该被下载,详细信息可以参见这里和这里的回答。当您执行请求时,Swagger UI会提供一个下载文件
链接,让您下载该文件。
headers = {'Content-Disposition': 'attachment; filename="Book.xlsx"'} return FileResponse(excel_file_path, headers=headers)
为了让浏览器直接展示文件,可以在Content-Disposition
头部中使用inline
参数,如前面的答案所述。然而,为了让浏览器能够展示Excel文件,您需要设置FileResponse
中的正确的media_type
(有关Excel文件的更多信息,请参见这里),并且浏览器必须已知.xlsx
(或.xls
)是一个合法的文件扩展名(通常可以通过浏览器扩展或插件实现)。