Trouble sending a file to Imgur
Asked Answered
A

3

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?

Agminate answered 11/7, 2012 at 16:45 Comment(0)
T
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})
Triparted answered 11/7, 2012 at 17:9 Comment(2)
How do we get link to the file uploaded?Phosphor
Had the same problem in Swift, but now it works. You are life saver!Mantis
M
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'
    }
)
Messene answered 11/7, 2012 at 17:10 Comment(0)
W
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?

Woodworker answered 11/7, 2012 at 16:55 Comment(1)
Good thought. Same error occurs. The code around open() is taken from the docs, too: docs.python-requests.org/en/latest/user/quickstart/…Agminate

© 2022 - 2024 — McMap. All rights reserved.