使用 httplib 使用 python 上传文件

发布于 2024-09-06 04:36:22 字数 851 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

牛↙奶布丁 2024-09-13 04:36:22

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

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

另外,附注:您可以将 open("h1.jpg", "rb") 直接传递到 < code>conn.request 而不先将其完全读入 chunk 中。 conn.request 接受类似文件的对象,一次传输一点文件会更有效:

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

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文