使用Python通过POST发送文件但不带有Content-Disposition

6

我在Python中使用requests模块发送POST请求来传输文件。 我的代码如下:

headers = {'Content-Type': 'application/x-tar',                         
           'Content-Length': tar_size}

r = requests.post(server,                             
                  files={"file": (tar_name, open(tar_name, 'rb'))},         
                  headers=headers)  

同一台服务器上,来自另一个使用C编写的客户端的文件也是以相同的方式发送的。当读取body_file(参见此处的webob内容:http://docs.webob.org/en/stable/api/request.html)时,来自C客户端的文件会被读取,然而来自我在Python中使用的客户端的实际文件则会被添加前缀:

--2a95cc93056b45e0b7c3447234788e29
Content-Disposition: form-data; name="file"; filename="filename.tar"

有没有一种方法可以阻止我的客户端发送这些内容?或者有什么方法可以修复服务器,使其能够从C客户端和我的客户端读取(即使我们似乎发送了略微不同的消息)?

你的意思是只发送字节,什么都不要发送吗?那HTTP头怎么办? - Bemmu
在我看来,multipart/form-data编码确实需要“Content-Disposition”这些东西,所以C语言实现是否有误,或者是在自定义客户端和服务器之间定义了不同的协议?更多有用的信息请参见:https://dev59.com/Jmoy5IYBdhLWcg3wQ8AF - Bemmu
2个回答

5

我也遇到了POST请求体中出现不想要的Content-Disposition的问题。我是这样解决的:

requests.post(server, headers=headers, data=open(myFile, 'rb').read())

3

好的,我解决了这个问题。如果有人遇到同样的问题,我会在这里发布我的解决方案。

解决方案是使用准备请求http://docs.python-requests.org/en/master/user/advanced/#prepared-requests)然后我可以按照所需的形式将数据放入正文中。我的代码现在看起来像这样:

headers = {'Content-Type': 'application/x-tar',                         
           'Content-Size': tar_size}

req = requests.Request('POST',
                       server,
                       headers)       

prepped = req.prepare()
with open(tar_name, 'rb') as f:
    prepped.body = fl.read(tar_size)

s = Request.Session()  
r = s.send(prepped,
           stream=True)                              

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接