2

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?

pnuts
  • 58,317
  • 11
  • 87
  • 139
hookedonwinter
  • 12,436
  • 19
  • 61
  • 74

3 Answers3

4

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})
ernie
  • 6,356
  • 23
  • 28
2

Have you tried being explicit with something like the following?:

from base64 import b64encode

requests.post(
    url, 
    data = {
        'key': api_key, 
        'image': b64encode(open('file1.png', 'rb').read()),
        'type': 'base64',
        'name': 'file1.png',
        'title': 'Picture no. 1'
    }
)
pnuts
  • 58,317
  • 11
  • 87
  • 139
0

Maybe you want open('test.png','rb').read() since open('test.png','rb') is a file object rather than the contents of the file?

DrSkippy
  • 390
  • 1
  • 3
  • Good thought. Same error occurs. The code around `open()` is taken from the docs, too: http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file – hookedonwinter Jul 11 '12 at 16:59