'How to post image using requests?

StackOverflow. I try to post an image using requests via python and I have tried so many ways to do but still no ideas.

here's the website : https://ezgif.com/image-to-datauri



Solution 1:[1]

import requests
url = 'http://localhost:5000/xxxx'
files = {'image_file': open('test2.png', 'rb')}
requests.post(url, files=files)

On the receiving side you can use

f = request.files['image_file']

This f will be in the form of bytes, you will have to decode bytes in the form of image. To do that using opencv you can use the following code

npimg = np.fromstring(f.read(), np.uint8)
img = cv2.imdecode(npimg, cv2.IMREAD_ANYCOLOR)

Solution 2:[2]

This is next to impossible to give a good answer without knowing more detail; What the API endpoint will accept, what you've already tried, etc. However, this is generally how you would upload a file in requests:

with open("/file/path.jpg") as fhandle:
   resp = requests.put("http://endpoint/address", data=fhandle.read(), headers={
                            "Content-Type": "{{ENTER_CONTENT_TYPE_HERE}}",
                        })

You can then access the status code from the 'resp' object to check success etc. The 'put' method is interchangeable with 'post' or whatever HTTP method you are using. I assume you are familiar with generally how to use the library.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Akash Basudevan
Solution 2 Michael