使用POST从Python脚本发送文件

发布于 2021-02-02 23:13:22

有没有一种方法可以使用Python脚本中的POST发送文件?

关注者
0
被浏览
93
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    通过请求,上传Multipart编码的文件非常简单:

    with open('report.xls', 'rb') as f:
        r = requests.post('http://httpbin.org/post', files={'report.xls': f})
    

    而已。我不是在开玩笑-这是一行代码。文件已发送。让我们检查:

    >>> r.text
    {
      "origin": "179.13.100.4",
      "files": {
        "report.xls": "<censored...binary...data>"
      },
      "form": {},
      "url": "http://httpbin.org/post",
      "args": {},
      "headers": {
        "Content-Length": "3196",
        "Accept-Encoding": "identity, deflate, compress, gzip",
        "Accept": "*/*",
        "User-Agent": "python-requests/0.8.0",
        "Host": "httpbin.org:80",
        "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"
      },
      "data": ""
    }
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看