需要使用的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)