Search code examples
pythonpython-requestsmultipartform-dataimgur

Trouble sending a file to Imgur


I'm trying to use the python requests lib to upload an image to Imgur using the imgur api. The api returns a 400, saying that the file is either not a supported file type or is corrupt. I don't think the image is corrupt (I can view it fine locally), and I've tried .jpg, .jpeg, and .png. Here is the code:

api_key = "4adaaf1bd8caec42a5b007405e829eb0"
url = "http://api.imgur.com/2/upload.json"
r = requests.post(url, data={'key': api_key, 'image':{'file': ('test.png', open('test.png', 'rb'))}})

The exact error message:

{"error":{"message":"Image format not supported, or image is corrupt.","request":"\/2\/upload.json","method":"post","format":"json","parameters":"image = file, key = 4adaaf1bd8caec42a5b007405e829eb0"}}

Let me know if I can provide more information. I'm pretty green with Python, and expect it's some simple misstep, could someone please explain what?


Solution

  • I'm just guessing, but looking at the imgur api, it looks like image should be just the file data, while the requests library is wrapping it into a key value pair (hence why the response shows "image = file")

    I'd try something like:

    import base64
    api_key = "4adaaf1bd8caec42a5b007405e829eb0"
    url = "http://api.imgur.com/2/upload.json"
    fh = open('test.png', 'rb');
    base64img = base64.b64encode(fh.read())
    r = requests.post(url, data={'key': api_key, 'image':base64img})