【问题标题】:Python: Upload a file in chunk to a server including additional fieldsPython:将文件分块上传到服务器,包括附加字段
【发布时间】:2025-12-01 07:05:01
【问题描述】:

我在这里原谅自己......我是一个 HTTP 菜鸟......但我需要创建一个 python 脚本,它接收一个文件并将其上传到一个包含附加数据的块中的服务器。

编辑:这只是我想要上传的一个文件......但在块中

所以我开始研究并遇到了pycurl,这似乎很复杂。所以我继续使用requests,它看起来非常漂亮和直观。

而且基本上我得到了它的部分工作......但是......并不是所有的结合起来:)

我发现我可以使用生成器来提供我的数据块。棒极了!但我还需要发送(对不起......我的词汇量非常有限)多部分边界???其他包含 JSON 信息的字段...

所以我的请求应该是这样的:

POST / HTTP/1.1
Host: some server
Content-Type: multipart/form-data;

Connection: Keep Alive
Transfer-Encoding: chunked

--boundary
Content-Disposition: form-data; name="Name of my field"
Content-Type: application/JSON; charset=utf-8
Content-Transfer-Encoding: 8bit

{"Some" : "content", "in" : "here"}

--boundary
Content-Disposition: form-data; name="My File"
Content-Type: audio/mpeg
Content-Transfer-Encoding: binary

... chunk 1 ....

--boundary
Content-Disposition: form-data; name="My File"
Content-Type: audio/mpeg
Content-Transfer-Encoding: binary

... chunk 2 ....

and so on...

我想我可以使用生成器创建分块上传。而且我还发现我可以使用file= 选项创建非文件边界。

但问题是我不能同时使用 :( 并且当使用我的生成器时,我无法定义我的块的 Content-Type,也不能定义名称......

再次...抱歉我的词汇不好:)

非常感谢任何帮助

【问题讨论】:

    标签: python http post python-requests pycurl


    【解决方案1】:
    import requests
    import json
    
    #from here http://*.com/a/23816211/642096
    def pretty_print_POST(req):
        """
        At this point it is completely built and ready
        to be fired; it is "prepared".
    
        However pay attention at the formatting used in 
        this function because it is programmed to be pretty 
        printed and may differ from the actual request.
        """
        print('{}\n{}\n{}\n\n{}'.format(
            '-----------START-----------',
            req.method + ' ' + req.url,
            '\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),
            req.body,
        ))
    
    url = 'http://httpbin.org/post'
    data = {'input_name': json.dumps({
        'json': 'here'
    })}
    files = {
        'file1': ('doc.txt', open('/tmp/doc.txt', 'rb'), 'text/plain'),
        'file2': ('doc2.html', open('/tmp/doc2.html', 'rb'), 'text/html'),    
    }
    r = requests.post(url, data=data, files=files)
    pretty_print_POST(r.request)
    print r.text
    

    【讨论】:

    • 我真的不明白这对我有什么帮助?因为您的示例中doc.txtdoc2.html 的内容没有分块上传...我想定义这些文件的每个字节应该有多少字节...