Failed to send file to Imgur

I am trying to use python lib requests to load an image in Imgur using imgur api . Api returns 400, stating that the file is either unsupported or corrupt. I do not think the image is damaged (I can view it locally) and I 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 is:

 {"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 am pretty green with Python and expect this to be a simple blunder, can anyone explain what?

+3
source share
3 answers

I just guess, but looking at the imgur api, it looks like the image should be just file data, and the request library is a pair of key values ​​(hence the answer shows "image = file",)

I would 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}) 
+4
source

Have you tried to be 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' } ) 
+2
source

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

0
source

All Articles