PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 29, 2022

[FIXED] how to send image to an API in micropython language

 July 29, 2022     api, esp8266, flask, image, micropython     No comments   

Issue

I am trying to send image through API in Micropython. still no solution how to do it. please help

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)

Solution

Maybe this template can help you :

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

You need to declare an header for your request



Answered By - Jonathan Delean
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing