开发者

Upload a file with python using httplib

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

Above is the site "www.encodable.com/uploaddemo/" where I want to upload an image.

开发者_StackOverflow中文版

I am better versed in php so I am unable to understand the meaning of path and headers here. In the code above, chunk is an object consisting of my image file. The following code produces an error as I was trying to implement without any knowledge of headers and path.

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


Currently, you aren't using the headers you've declared earlier in the code. You should provide them as the fourth argument to conn.request:

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

Also, side note: you can pass open("h1.jpg", "rb") directly into conn.request without reading it fully into chunk first. conn.request accepts file-like objects and it will be more efficient to stream the file a little at a time:

conn.request("POST", "/uploaddemo/files/", open("h1.jpg", "rb"), headers)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜