【问题标题】:post multipart image to api将多部分图像发布到 api
【发布时间】:2014-11-21 21:08:18
【问题描述】:

用邮递员发帖:

请求负载:

------WebKitFormBoundaryiPTu5XrX314NHpan
Content-Disposition: form-data; name="photo"; filename="example1.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryiPTu5XrX314NHpan--

在标题中:

Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryiPTu5XrX314NHpan

需要从 python 应用程序发送图像,但每次都收到 400 错误。

尝试:

req = urllib2.Request(photoURL, None, {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'})
imgFile = cStringIO.StringIO(urllib2.urlopen(req).read())
datagen, headers = multipart_encode({"photo": Image.open(imgFile)})
request = urllib2.Request(postPhotoAPI, datagen, headers)
request.add_header("Authorization", authKey)
urllib2.urlopen(request).read()

结果:400

在 requests.post 和其他一些 post 函数中相同(也适用于 base64)。

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    当我想用 python 进行 http 调用时,我总是使用 python requests 库。

    你需要做这样的事情:

    files = {'photo': ('image.png', open('image.png', 'rb'), 'image/png')}
    r = requests.post(photoURL, header={'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5', 'Authorization': authKey} files=files)
    print r.text
    

    您可以阅读更多here

    【讨论】:

    • 谢谢,对我帮助很大。不知道requests中有选项文件。
    猜你喜欢
    • 2017-09-20
    • 2013-01-15
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多