如何使用 Python Requests 库上传文件

下面是使用 Python Requests 库上传文件的示例。在深入探讨文件上传示例之前,让我们确保你已经安装了 requests 库。如果没有,你可以使用 pip 安装它:

pip install requests

下面是使用 Python Requests 库上传文件的方法:

  • 使用 files 参数
  • 使用 data 参数
  • 直接使用 multipart/form-data
  • 作为原始二进制数据发送

文件结构

!Screenshot-2024-03-21-144350

file.txt

GeeksforGeeks

使用 Files 参数上传文件

在这个例子中,下面的代码使用 Python requests 库通过 POST 请求将文件 (file.txt) 上传到指定的 URL (https://httpbin.org/post) ,使用 files 参数,然后打印响应文本。

Python3


CODEBLOCK_3ff6369d

Output

{
  "args": {}, 
  "data": "", 
  "files": {
    "file": "GeeksforGeeks"
  }, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "157", 
    "Content-Type": "multipart/form-data; boundary=c4e3e1f85303491ffd523537762f87bc", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.31.0", 
    "X-Amzn-Trace-Id": "Root=1-65fbfabc-4d943f6b5851070275fbb946"
  }, 
  "json": null, 
  "origin": "157.34.0.92", 
  "url": "https://httpbin.org/post"
}

使用 Data 参数上传文件

在这个例子中,下面的 Python 代码向 "https://httpbin.org/post" 发送一个 POST 请求 t,其中包含表单数据 (‘key‘: ‘value‘) 和通过 requests 库上传的文件 (‘file.txt‘)。然后打印从服务器收到的响应。

Python3


CODEBLOCK_06b9374c

Output

{
  "args": {}, 
  "data": "", 
  "files": {
    "file": "GeeksforGeeks"
  }, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "157", 
    "Content-Type": "multipart/form-data; boundary=c4e3e1f85303491ffd523537762f87bc", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.31.0", 
    "X-Amzn-Trace-Id": "Root=1-65fbfabc-4d943f6b5851070275fbb946"
  }, 
  "json": null, 
  "origin": "157.34.0.92", 
  "url": "https://httpbin.org/post"
}

直接使用 Multipart/Form-data 上传文件

在这个例子中,下面的 Python 代码使用 requests 库对 https://httpbin.org/post 执行 POST 请求,上传文件 example.txt 并指定内容类型为 multipart/form-data。然后打印服务器的响应。

Python3


CODEBLOCK_339393b0

Output

{
  "args": {}, 
  "data": "", 
  "files": {
    "file": "GeeksforGeeks"
  }, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "157", 
    "Content-Type": "multipart/form-data; boundary=c4e3e1f85303491ffd523537762f87bc", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.31.0", 
    "X-Amzn-Trace-Id": "Root=1-65fbfabc-4d943f6b5851070275fbb946"
  }, 
  "json": null, 
  "origin": "157.34.0.92", 
  "url": "https://httpbin.org/post"
}

作为原始二进制数据发送

在这个例子中,下面的代码向 ‘https://httpbin.org/post‘ 发送一个 POST 请求,头部指定内容类型为 ‘application/octet-stream‘。它将文件 ‘file.txt‘ 的内容作为原始二进制数据上传。然后打印服务器的响应。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/25846.html
点赞
0.00 平均评分 (0% 分数) - 0