使用httplib使用python上传文件 [英] Upload a file with python using httplib

查看:143
本文介绍了使用httplib使用python上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

上面是我要上传图像的网站"www.encodable.com/uploaddemo/".

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

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

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

推荐答案

当前,您没有使用代码中先前声明的标头.您应该将它们作为conn.request的第四个参数:

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)

此外,请注意:您可以将open("h1.jpg", "rb")直接传递到conn.request,而无需先将其完全读入chunk. conn.request接受类似文件的对象,并且一次流一点文件会更有效:

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)

这篇关于使用httplib使用python上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆