
本文介绍了如何在 FastAPI 框架中实现文件上传,并同时接收其他数据。通过结合 UploadFile 类型和请求参数,可以轻松构建支持文件上传和数据传递的 API 接口,解决在处理复杂业务场景时,需要同时上传文件和传递相关元数据的需求。
FastAPI 提供了强大的文件上传功能,结合请求参数,可以方便地实现文件上传和数据传递。以下是如何在 FastAPI 中实现这一功能的详细步骤和示例。
实现方法
FastAPI 使用 UploadFile 类型来处理文件上传。你可以将 UploadFile 作为函数参数,并结合其他参数来接收额外的数据。
示例代码
from fastapi import FastAPI, UploadFile, File
app = FastAPI()
@app.post("/upload")
async def upload_file(
file: UploadFile = File(...), transaction_id: str = None, organization_id: str = None
):
"""
上传文件并接收 transaction_id 和 organization_id。
"""
file_name = f"{organization_id}_{transaction_id}_{file.filename}" # 拼接文件名,包含原始文件名
try:
contents = await file.read() # 使用 await 读取文件内容
with open(file_name, "wb") as f:
f.write(contents)
except Exception as e:
return {"message": f"There was an error uploading the file: {e}"}
finally:
await file.close() # 使用 await 关闭文件
return {"filename": file_name, "message": "File uploaded successfully"}代码解释
注意事项
总结
通过结合 UploadFile 类型和请求参数,可以轻松实现 FastAPI 中的文件上传和数据传递。在实际应用中,需要注意文件大小限制、文件类型验证、异常处理和文件名安全等问题。使用异步函数可以提高应用的性能。
以上就是FastAPI 实现文件上传与数据传递的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号