如何使用micropython语言将图像发送到API

问题描述 投票:0回答:1

我正在尝试通过Micropython中的API发送图像。仍然没有解决办法。请帮助

import urequests
import json
URL = 'https://example.com/test'
datas = json.dumps({"auth_key": "43435", "mac": "abcd", "name": "washid"})
filep = 'OBJ.jpg'
filess = {'odimg': open(filep, 'rb')}
try:
    response = urequests.post(URL,data=datas,files=files)
    print(response.json())
except Exception as e:
    print(e)
image api flask esp8266 micropython
1个回答
0
投票

也许此模板可以帮助您:

import ubinascii
import uos
import urequests


def make_request(data, image=None):
    boundary = ubinascii.hexlify(uos.urandom(16)).decode('ascii')

    def encode_field(field_name):
        return (
            b'--%s' % boundary,
            b'Content-Disposition: form-data; name="%s"' % field_name,
            b'', 
            b'%s'% data[field_name]
        )

    def encode_file(field_name):
        filename = 'latest.jpeg'
        return (
            b'--%s' % boundary,
            b'Content-Disposition: form-data; name="%s"; filename="%s"' % (
                field_name, filename),
            b'', 
            image
        )

    lines = []
    for name in data:
        lines.extend(encode_field(name))
    if image:
        lines.extend(encode_file('file'))
    lines.extend((b'--%s--' % boundary, b''))
    body = b'\r\n'.join(lines)

    headers = {
        'content-type': 'multipart/form-data; boundary=' + boundary,
        'content-length': str(len(body))}
    return body, headers


def upload_image(url, headers, data):
    http_response = urequests.post(
        url,
        headers=headers,
        data=data
    )
    if http_response.status_code == 204:
        print('Uploaded request')
    else:
        raise UploadError(http_response)
    http_response.close()
    return http_response

您需要为您的请求声明标题

© www.soinside.com 2019 - 2024. All rights reserved.