服务端
@app.post("/uploadM")
async def upload(file: UploadFile = File(...)):
contents = await file.read()
# with open(file.filename, 'wb') as f:
with open("filename.jpg", 'wb') as f:
f.write(contents)
await file.close()
@app.post("/upload")
async def upload(file: UploadFile = File(...)):
try:
contents = await file.read()
with open(file.filename, 'wb') as f:
f.write(contents)
except Exception:
return {"message": "There was an error uploading the file"}
finally:
await file.close()
return {"message": f"Successfuly uploaded {file.filename}"}
客户端
img=cv2.imread("xx.jpg")
success, encoded_image = cv2.imencode(".jpg", img)
# 将数组转为bytes
img_bytes = encoded_image.tobytes()
url = 'http://0.0.0.0:9000/uploadM'
file = {'file': img_bytes}
resp = requests.post(url=url, files=file)
print(resp.json())
参考文章
- https://stackoverflow.com/questions/63048825/how-to-upload-file-using-fastapi
- https://pyquestions.com/how-do-i-return-an-image-in-fastapi
- 官网 https://fastapi.tiangolo.com/tutorial/response-model/
- https://stackoverflow.com/questions/61333907/receiving-an-image-with-fast-api-processing-it-with-cv2-then-returning-it
- https://testdriven.io/blog/fastapi-streamlit/
- https://icode.best/i/19214743170886
- https://stackoverflow.com/questions/65408109/how-do-i-receive-image-and-json-data-in-fastapi
- https://dailydevsblog.com/troubleshoot/resolved-how-can-i-return-a-numpy-array-using-fastapi-137875/
- https://stackoverflow.com/questions/71595635/render-numpy-array-in-fastapi/71639658#71639658
- https://codeantenna.com/a/syiFxEejDG