python文件上传

总结可行方案:

1.http.request传的参数中带fields时,带上特定的boundary(以WebKitFormBoundary开头的, 原因未知, 知道的朋友可以留言告知),headers中不要带Content-Type;

2.http.request传的参数要带上headers的话,格式应该是:Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

最终的代码修改:

urllib3.disable_warnings()
http = urllib3.PoolManager()
with open('example.jpeg','rb') as fp:

POST请求四种传递正文的方式
(1)请求正文是application/x-www-form-urlencoded
最常见的POST提交数据的方式,浏览器的原生form表单,如果不设置enctype属性,那么最终就会以application/x-www-form-urlencoded方式提交数据。

(2)multipart/form-data
上传文件的表单

(3)application/json
用来告诉服务器消息主体是序列化之后的JSON字符串。

(4)text/xml
它是一种使用HTTP作为传输协议,XML作为编码方式的远程调用规范。
 

    

urllib3.disable_warnings()

http = urllib3.PoolManager()

 file_data = fp.read()
boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW'
#方案1
r = http.request(
     'POST',
     'http://httpbin.org/post',
     headers = {},
     multipart_boundary = boundary,
     fields={
         'text': ('None', "upload a string",'None'),
         'file': ('example.jpeg',file_data,"image/jpeg"),
     })
 
 
#方案2
r = http.request(
     'POST',
     'http://httpbin.org/post',
     headers = {'Content-Type':"multipart/form-data;%s"%boundary},
     multipart_boundary = boundary,
     fields={
         'text': ('None', "upload a string",'None'),
         'file': ('example.jpeg',file_data,"image/jpeg"),
     })
 ———————————————— 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值