0

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

  • So many way? Please share it with us. – Florian Bernard Nov 11 '19 at 12:49
  • Welcome to Stackoverflow! Please post code in your **question post** showing what you have tried so far. Please describe or show the behavior you are getting from the code, and any error messages you are receiving. Also, please clearly state your *expected* behavior from the code. – Kevin Nov 11 '19 at 12:59

2 Answers2

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)
Akash Basudevan
  • 820
  • 5
  • 15
0

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.

Michael
  • 153
  • 1
  • 9