我有一个简单的文本文件,我想在任何锚标记链接上下载该文件.
但是,当我点击链接txt文件显示我但没有下载.
我试过这段代码
<html>
<head>
<title>File</title>
</head>
<body>
<a href="test.txt">Click here</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud) 有没有办法通过FastAPI下载文件?我们想要的文件位于 Azure Datalake 中,从数据湖中检索它们不是问题,当我们尝试将从数据湖获取的字节传输到本地计算机时,就会出现问题。
我们尝试过在 FastAPI 中使用不同的模块,例如starlette.responses.FileResponse和 ,fastapi.Response但没有成功。
在 Flask 中这不是问题,可以通过以下方式完成:
from io import BytesIO
from flask import Flask
from werkzeug import FileWrapper
flask_app = Flask(__name__)
@flask_app.route('/downloadfile/<file_name>', methods=['GET'])
def get_the_file(file_name: str):
the_file = FileWrapper(BytesIO(download_file_from_directory(file_name)))
if the_file:
return Response(the_file, mimetype=file_name, direct_passthrough=True)
Run Code Online (Sandbox Code Playgroud)
当使用有效的文件名运行此文件时,文件会自动下载。FastAPI 中有类似的方法吗?
经过更多的故障排除后,我找到了一种方法来做到这一点。
from fastapi import APIRouter, Response
router = APIRouter()
@router.get('/downloadfile/{file_name}', tags=['getSkynetDL'])
async def get_the_file(file_name: str):
# the_file object is raw bytes
the_file = download_file_from_directory(file_name)
if the_file:
return Response(the_file)
Run Code Online (Sandbox Code Playgroud)
因此,经过大量的故障排除和数小时的文档查看之后,这就是所需要的一切,只需将字节返回为Response(the_file).
我正在尝试创建一个docx文件并将其发送到前端客户端应用程序,以便可以将其下载到用户的本地计算机。我使用 FastAPI 作为后端。我还使用python-docx库来创建Document.
下面的代码用于创建一个docx文件并将其保存到服务器。
@app.post("/create_file")
async def create_file(data: Item):
document = Document()
document.add_heading("file generated", level=1)
document.add_paragraph("test")
document.save('generated_file.docx')
return {"status":"Done!"}
Run Code Online (Sandbox Code Playgroud)
然后使用以下代码将创建的docx文件作为 a发送FileResponse到客户端。
@app.get("/generated_file")
async def download_generated_file():
file_path = "generated_file.docx"
return FileResponse(file_path, media_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document', filename=file_path)
Run Code Online (Sandbox Code Playgroud)
在客户端(我正在使用 ReactJS):
@app.post("/create_file")
async def create_file(data: Item):
document = Document()
document.add_heading("file generated", level=1)
document.add_paragraph("test")
document.save('generated_file.docx')
return {"status":"Done!"}
Run Code Online (Sandbox Code Playgroud)
调用函数generated.docx时会下载文件。downloadFile但是,该docx文件始终已损坏并且无法打开。我尝试使用txt文件,效果很好。我需要使用docx文件,我该怎么办?
我正在尝试从 FastAPI 后端下载一个大文件 ( .tar.gz)。在服务器端,我只是验证文件路径,然后Starlette.FileResponse返回整个文件\xe2\x80\x94,就像我在 StackOverflow 上的许多相关问题中看到的那样。
服务器端:
\nreturn FileResponse(path=file_name, media_type=\'application/octet-stream\', filename=file_name)\nRun Code Online (Sandbox Code Playgroud)\n之后,我收到以下错误:
\n File "/usr/local/lib/python3.10/dist-packages/fastapi/routing.py", line 149, in serialize_response\n return jsonable_encoder(response_content)\n File "/usr/local/lib/python3.10/dist-packages/fastapi/encoders.py", line 130, in jsonable_encoder\n return ENCODERS_BY_TYPE[type(obj)](obj)\n File "pydantic/json.py", line 52, in pydantic.json.lambda\nUnicodeDecodeError: \'utf-8\' codec can\'t decode byte 0x8b in position 1: invalid start byte\nRun Code Online (Sandbox Code Playgroud)\n我也尝试使用StreamingResponse,但得到了同样的错误。还有其他方法可以做到吗?
我的代码中的StreamingResponse:
File "/usr/local/lib/python3.10/dist-packages/fastapi/routing.py", line 149, in serialize_response\n return jsonable_encoder(response_content)\n File "/usr/local/lib/python3.10/dist-packages/fastapi/encoders.py", line 130, in jsonable_encoder\n return ENCODERS_BY_TYPE[type(obj)](obj)\n File …Run Code Online (Sandbox Code Playgroud) 我将使用 FastAPI 创建一个 API HTML,使用pdfkit. 但是,它将文件保存到我的本地磁盘。当我在线提供此API后,用户如何将该PDF文件下载到他们的计算机上?
from typing import Optional
from fastapi import FastAPI
import pdfkit
app = FastAPI()
@app.post("/htmltopdf/{url}")
def convert_url(url:str):
pdfkit.from_url(url, 'converted.pdf')
Run Code Online (Sandbox Code Playgroud) 我发现如何使用 FastAPI 将 numpy 数组作为图像返回?然而,我仍然在努力展示图像,它看起来只是一个白色的方块。
io.BytesIO我像这样读入一个数组:
def iterarray(array):
output = io.BytesIO()
np.savez(output, array)
yield output.get_value()
Run Code Online (Sandbox Code Playgroud)
在我的端点中,我的回报是StreamingResponse(iterarray(), media_type='application/octet-stream')
当我留空media_type以推断时,会下载一个 zip 文件。
如何将数组显示为图像?
我正在为网站使用 Nextjs 前端和 FastAPI 后端。我在前端有一个“以太坊地址”的输入表单,并使用输入的地址,我在后端生成一个 matplotlib 图表,显示“一段时间内的以太坊余额”。现在,我尝试使用 FastAPI 返回此图表,以便可以在前端显示它。我不想在本地保存图表。
这是到目前为止我的相关代码:
前端/ nexjs 文件名为“Chart.tsx”。正文中的“ethAddress”正在捕获输入表单中输入的数据。
fetch("http://localhost:8000/image", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(ethAddress),
}).then(fetchEthAddresses);
Run Code Online (Sandbox Code Playgroud)
生成名为 ethBalanceTracker.py 的 matplotlib 图表的后端 python 文件
#Imports
#Logic for chart here
plt.plot(times, balances)
buf = BytesIO()
plt.savefig(buf, format="png")
buf.seek(0)
return StreamingResponse(buf, media_type="image/png")
Run Code Online (Sandbox Code Playgroud)
使用名为 api.py 的 FastAPI 的后端 python 文件
@app.get("/image")
async def get_images() -> dict:
return {"data": images}
@app.post("/image")
async def add_image(ethAddress: dict) -> dict:
test = EthBalanceTracker.get_transactions(ethAddress["ethAddress"])
images.append(test)
Run Code Online (Sandbox Code Playgroud)
我已经尝试了上面的代码和其他一些变体。我使用是StreamingResponse因为我不想在本地保存图表。我的问题是我无法显示图表localhost:8000/images并得到一个 …