我想發出一個 http POST 請求,并將影像作為multipart/form-data. 我想避免將此影像編碼為base64,而只是將其作為二進制blob發送,我知道http可以處理。
這是我在客戶端的代碼:
from __future__ import print_function
import requests
import json
import cv2
def post_encoded_image(url, headers):
img = open("cyrus.jpg", 'rb').read()
payload = {'image': img, 'identity': 'cyrus'}
r = requests.post(url "encoded-image", data=payload)
print(r)
url = "http://localhost:8080/"
content_type = 'multipart/form-data'
headers = {'content-type': content_type}
post_encoded_image(url, headers)
在服務器端,我的代碼如下所示:
from flask import Flask, request
import flask
import tfsdk
import numpy as np
from colorama import Fore
from colorama import Style
import os
import cv2
@app.route('/encoded-image', methods=['POST'])
def test():
image = request.form.get("image")
nparr = np.fromstring(image, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
print(type(img))
return "success"
if __name__ == '__main__':
app.run()
當我發出請求時,服務器會列印imgas的型別NoneType,這意味著呼叫imdecode不起作用,這意味著服務器端正在使用編碼影像發生一些奇怪的事情。
這樣做的正確方法是什么?
編輯 我能夠通過執行以下操作來實作所需的功能:
客戶:
from __future__ import print_function
import requests
import json
import cv2
def post_encoded_image(url, headers):
img = open("cyrus.jpg", 'rb').read()
file = {'image': img}
data = {'identity': 'cyrus'}
r = requests.post(url "encoded-image", data=data, files=file)
print(r)
url = "http://localhost:8080/"
content_type = 'multipart/form-data'
headers = {'content-type': content_type}
post_encoded_image(url, headers)
服務器:
@app.route('/encoded-image', methods=['POST'])
def test():
ID = request.form.get("identity")
image = request.files['image'].read()
nparr = np.fromstring(image, np.uint8)
這是正確的做法嗎?
uj5u.com熱心網友回復:
我能夠實作如下所需的功能:
客戶:
from __future__ import print_function
import requests
import json
import cv2
def post_encoded_image(url, headers):
img = open("cyrus.jpg", 'rb').read()
file = {'image': img}
data = {'identity': 'cyrus'}
r = requests.post(url "encoded-image", data=data, files=file)
print(r)
url = "http://localhost:8080/"
content_type = 'multipart/form-data'
headers = {'content-type': content_type}
post_encoded_image(url, headers)
服務器:
@app.route('/encoded-image', methods=['POST'])
def test():
ID = request.form.get("identity")
image = request.files['image'].read()
nparr = np.fromstring(image, np.uint8)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/452972.html
