file-upload - 将小文件上传到 FastAPI 端点,但上传文件内容为空

标签 file-upload fastapi starlette

我正在尝试将文件 (csv) 上传到 FastAPI POST 端点。

这是服务器代码:

@app.post("/csv/file/preview")
async def post_csv_file_preview(file: UploadFile):
    """

    :param file:
    :return:
    """
    contents = file.file.read()
    print(contents)

但是如果文件很小,内容是空的。如果我增加文件内容(在 csv 文件中添加新行),而没有任何其他更改,则它可以正常工作。

如果直接获取请求体,则正常返回文件内容。

print(await request.body())

问题仅出在我的生产服务器上,而不是本地:

PYTHONPATH=/var/www/api/current /var/www/api/current/venv/bin/python /var/www/api/current/venv/bin/uvicorn main:app --reload --port=8004

我听不懂

最佳答案

感谢 Chris 的评论,我通过在读取文件内容之前添加 .seek() 方法解决了我的问题。

@app.post("/csv/file/preview")
def post_csv_file_preview(file: UploadFile):
    """

    :param file:
    :return:
    """
    file.file.seek(0)
    contents = file.file.read()
    print(contents)

关于file-upload - 将小文件上传到 FastAPI 端点,但上传文件内容为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73632237/

相关文章:

postgresql - 连接被拒绝 : Is the server running on host "db" (172. 21.0.2) 并接受端口 5432 上的 web_1 TCP/IP 连接?

python - FastAPI,返回带有SQL查询输出的File响应

javascript - file_put_contents() : failed to open stream

java - 如何使用JSP/Servlet将文件上传到服务器?

python - 如何将 SQLAlchemy 结果行转换为嵌套的字典

python-3.x - Nginx proxy_pass 到 docker 容器不起作用

python - FastAPI 中间件查看响应

python - 如何在FastAPI中间件中修改响应后的内容长度?

Java:使用 Oreilly MultipartRequest servlet 发送带有附件的电子邮件

java - 使用 Jersey 客户端上传文件的最佳方法是什么?