Q:

how to upload image using kivy UrlRequest

//library that can determine filetypes from binary data
import imghdr
from urllib.parse import urlencode

import kivy.properties as kp
from kivy.event import EventDispatcher
from kivy.network.urlrequest import UrlRequest

/constructs multi-part/form data from a file (needed to POST to a server via http)
from requests_toolbelt import MultipartEncoder

SLACK_IMAGE_URL = 'https://slack.com/api/files.upload'

class SlackClient(EventDispatcher):

    slack_token = kp.ConfigParserProperty(
        "",
        "Slack",
        "slack_api_token",
        "app"
    )

    default_channel = kp.ConfigParserProperty(
        "",
        "Slack",
        "slack_default_channel",
        "app"
    )

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def image_test(self, *args):

        with open('my_image', 'rb') as f:
            my_image = f.read()

        //returns 'png' or 'jpg'
        image_type = imghdr.what(None, h=my_image)

        mime_type = f"image/{image_type}"

        //constructs the POST PAYLOAD
        payload = MultipartEncoder(
            fields={
                'file': (
                    'my_image.png', 
                    my_image,
                    mime_type
                )
            }
        )

        headers = {
            'Authorization': f"Bearer {self.slack_token}",
            'Content-Type': payload.content_type
        }

        querystring = {"channels":"my_slack_channel"}
        slack_query = urlencode(querystring)

        url = f"{SLACK_IMAGE_URL}?{slack_query}"

        //req_body parameter makes this a POST instead of a GET
        UrlRequest(
            url, 
            on_success = self.got_success, 
            on_redirect = self.got_redirect,
            on_failure = self.got_fail,
            on_error = self.got_error,
            req_headers = headers,
            req_body=payload,
            verify = False
        )
0

New to Communities?

Join the community