Trouble sending a file to Imgur

自古美人都是妖i 提交于 2019-12-13 12:17:37

问题


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?


回答1:


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})



回答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'
    }
)



回答3:


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



来源:https://stackoverflow.com/questions/11437444/trouble-sending-a-file-to-imgur

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!