欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

FastApi 文件上传upload

程序员文章站 2022-06-13 16:02:34
...

需要使用的Python包:fastapi和uvicorn。

import time
import uvicorn
from fastapi import FastAPI, File, UploadFile

app = FastAPI()


@app.post("/file_upload")
async def file_upload(file: UploadFile = File(...)):
    start = time.time()
    try:
        res = await file.read()
        with open(file.filename, "wb") as f:
            f.write(res)
        return {"message": "success", 'time': time.time() - start, 'filename': file.filename}
    except Exception as e:
        return {"message": str(e), 'time': time.time() - start, 'filename': file.filename}


if __name__ == '__main__':
    uvicorn.run(app=app, host="127.0.0.1", port=8000, workers=1)

客户端代码示例

import requests
url = "http://127.0.0.1:8000/file_upload"
path = "C:\\Users\\omegaxyz\\Desktop\\pic.jpeg"
files = {'file': open(path, 'rb')}
r = requests.post(url, files=files)
print(r.url)
print(r.text)
相关标签: python