python - 使用 POST 从 Python 脚本发送文件

有没有办法通过 Python 脚本使用 POST 发送文件?

最佳答案

发件人:https://requests.readthedocs.io/en/latest/user/quickstart/#post-a-multipart-encoded-file

Requests 让上传多部分编码文件变得非常简单:

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": ""
}

https://stackoverflow.com/questions/68477/

相关文章:

python - 如何在当前模块上调用 setattr()?

linux - 监听网络端口并将数据保存到文本文件

linux - 是否有将随机垃圾字节写入文件的命令?

linux - Crontab 每 15 分钟运行一次,除了凌晨 3 点?

c - 如何捕获 Control+D 信号?

linux - 如何给 Linux 用户 sudo 访问权限?

python - 如何在 Anaconda (Conda) 环境中跟踪 pip 安装的软件包?

python - 为什么 PyCharm 建议将方法更改为静态?

python - 排除 os.walk 中的目录

linux - 未生成核心转储文件