使用 httplib 使用 python 上传文件
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()
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.
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
目前,您没有使用之前在代码中声明的标头。您应该将它们作为
conn.request
的第四个参数提供:另外,附注:您可以将
open("h1.jpg", "rb")
直接传递到 < code>conn.request 而不先将其完全读入chunk
中。 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
:Also, side note: you can pass
open("h1.jpg", "rb")
directly intoconn.request
without reading it fully intochunk
first.conn.request
accepts file-like objects and it will be more efficient to stream the file a little at a time: