【问题标题】:upload file with post params使用 post 参数上传文件
【发布时间】:2015-10-14 20:27:20
【问题描述】:

我想将文件发送到带有一些帖子参数的网址,例如“chat_id”、“标题”,并且文件必须作为“照片”字段名发送。
但我找到了只发送不带文件的 POST 参数或只发送不带 POST 参数和自定义文件名参数的文件的方法。
此代码仅发送params 字段,但我还需要files 字段。

from urllib import parse, request
...
files={'photo': open('file.jpg','rb')}          
params = parse.urlencode({'chat_id': chat_id, 'caption': 'test'})
#headers = {"Content-type": "multipart/form-data"}      

req = request.Request(url, params.encode('ascii'))
response = request.urlopen(req)
print(response.read())

Python 3.4.2

【问题讨论】:

    标签: python-3.x file-upload request http-post


    【解决方案1】:

    好的。我找到了解决方案。
    我安装了外部库Requests: HTTP for Humans
    现在我正在使用requests

    import requests
    ...
    url = 'https://api.telegram.org/bot'+self.token+'/sendPhoto' #'/sendmessage'
    print('request to '+url+' with params '+chat_id+' ' + text)     
    
    headers = {'Content-Type': 'multipart/form-data'}
    
    files = {'photo': open('file.jpg', 'rb')}
    params = {'chat_id': chat_id, 'caption': text}
    r = requests.post(url,  files=files, params=params)     
    print(r.text)   
    

    【讨论】:

      猜你喜欢
      • 2013-03-16
      • 2014-02-14
      • 1970-01-01
      • 2020-05-11
      • 2018-04-18
      • 1970-01-01
      • 2012-06-18
      • 2011-04-22
      • 1970-01-01
      相关资源
      最近更新 更多