1
conn = httplib.HTTPConnection("www.encodable.com/uploaddemo/")
conn.request("POST", path, chunk, headers)

以上是我要上传图片的网站“www.encodable.com/uploaddemo/”。

我比较精通,php所以我无法理解这里的路径和标题的含义。在上面的代码中,chunk是一个由我的图像文件组成的对象。当我在不了解标头和路径的情况下尝试实现时,以下代码会产生错误。

import httplib

def upload_image_to_url():

    filename = '//home//harshit//Desktop//h1.jpg'
    f = open(filename, "rb")
    chunk = f.read()
    f.close()

    headers = {
        "Content−type": "application/octet−stream",
        "Accept": "text/plain"
    }

    conn = httplib.HTTPConnection("www.encodable.com/uploaddemo/")
    conn.request("POST", "/uploaddemo/files/", chunk)

    response = conn.getresponse()
    remote_file = response.read()
    conn.close()
    print remote_file

upload_image_to_url()
4

1 回答 1

5

目前,您没有使用之前在代码中声明的标头。您应该将它们作为第四个参数提供给conn.request

conn.request("POST", "/uploaddemo/files/", chunk, headers)

另外,附注:您可以open("h1.jpg", "rb")直接进入conn.request,而无需先完全阅读chunkconn.request接受类似文件的对象,并且一次流一点文件会更有效:

conn.request("POST", "/uploaddemo/files/", open("h1.jpg", "rb"), headers)
于 2010-06-20T14:33:39.797 回答