Python:将图像发送到FlaskAPI,以存储在服务器上供进一步使用
我正在尝试向Flask API发送图像。到目前为止,我使用base64对要作为字符串发送的图像进行编码。在服务器端,我接收该字符串并对其进行解码,然后尝试在服务器端写入文件。代码运行,但生成的JPG不可见,它显示“看起来我们不支持这种格式。”我还尝试将该文件保存为其他照片文件格式。这是一个我转换成字符串的jpg,这就是为什么我保存为jpg 这是我的客户端代码:Python:将图像发送到FlaskAPI,以存储在服务器上供进一步使用,python,flask,Python,Flask,我正在尝试向Flask API发送图像。到目前为止,我使用base64对要作为字符串发送的图像进行编码。在服务器端,我接收该字符串并对其进行解码,然后尝试在服务器端写入文件。代码运行,但生成的JPG不可见,它显示“看起来我们不支持这种格式。”我还尝试将该文件保存为其他照片文件格式。这是一个我转换成字符串的jpg,这就是为什么我保存为jpg 这是我的客户端代码: with open(filename, "rb") as img: string = base64.b64e
with open(filename, "rb") as img:
string = base64.b64encode(img.read())
print(type(string))
print(string)
name = 'John Doe'
EmpID = 1
company = 1
def test():
api_url = "http://192.168.8.13:5000/register-new?emp_name=%s&company_id=%s&emp_id=%s&user_photo=%s" % (name, company, EmpID, string)
response = requests.post(url= api_url)
assert response.status_code == 200
这是接收照片的服务器端代码
photo = request.args.get('user_photo')
photo1 = photo.replace(" ", "")
f = (base64.b64decode(photo1))
a = io.BytesIO()
with open("compare.jpg", "wb") as file:
file.write(f)
如果您真的想将其作为base64数据上传,我建议将其作为JSON放到post正文中,而不是作为GET参数 在客户端,按如下方式打开文件:
with open(filename, "rb") as img:
string = base64.b64encode(img.read()).decode('utf-8')
然后在test
函数中,从URL中取出image\u数据
字符串,并使用request.post
参数json
以正确的内容类型传递该字符串。您可以考虑将其他变量添加到用这个ARG传递的字典:
def test():
api_url = "http://192.168.8.13:5000/register-new?emp_name=%s&company_id=%s&emp_id=%s" % (name, company, EmpID)
response = requests.post(url= api_url, json={'user_photo':string})
然后在后端,通过Flask的请求获取此数据。获取_json
函数并初始化BytesIO
对象,然后将数据写入该对象,最后写入文件:
@app.route('/register-new', methods=['POST'])
def register_new():
photo = request.get_json()['user_photo']
photo_data = base64.b64decode(photo)
with open("compare.jpg", "wb") as file:
file.write(photo_data)
对于测试映像,这可以正常工作,如Linux文件
命令所确认:
$ file compare.jpg
compare.jpg: JPEG image data, baseline, precision 8, 500x750, components 3