使用 form-data 和 SpooledTemporaryFile 使用 FastAPI 上传文件
要使用带有 multipart/form-data 的 FastAPI 上传文件,建议安装python-multipart 作为多部分文件通过发送form-data。
pip install python-multipart
这是使用 FastAPI 上传文件的改进示例:
from fastapi import File, UploadFile from typing import List @app.post("/upload") def upload(file: UploadFile = File(...)): try: # Using file.file for synchronous operations (e.g., opening a file on disk) contents = file.file.read() with open(file.filename, 'wb') as f: f.write(contents) except Exception: return {"message": "An error occurred while uploading the file."} finally: file.file.close() return {"message": f"Successfully uploaded {file.filename}"}
如果您需要分块处理较大的文件,请考虑以较小的增量读取文件。您可以使用手动循环:
@app.post("/upload") def upload(file: UploadFile = File(...)): try: with open(file.filename, 'wb') as f: while contents := file.file.read(1024 * 1024): f.write(contents) except Exception: return {"message": "An error occurred while uploading the file."} finally: file.file.close() return {"message": f"Successfully uploaded {file.filename}"}
或者使用 Shutil.copyfileobj() 方法,该方法以块的形式读取和写入数据:
from shutil import copyfileobj @app.post("/upload") def upload(file: UploadFile = File(...)): try: with open(file.filename, 'wb') as f: copyfileobj(file.file, f) except Exception: return {"message": "An error occurred while uploading the file."} finally: file.file.close() return {"message": f"Successfully uploaded {file.filename}"}
附加说明:
以上是如何使用'form-data”高效地将文件上传到FastAPI服务器?的详细内容。更多信息请关注PHP中文网其他相关文章!