本文将介绍如何使用 Python 的 requests 库上传文件。

以下是一个示例代码,演示如何使用 Python 的 requests 库上传文件:

import requests

url = 'http://httpbin.org/post'  # 目标 URL
file_path = 'path/to/file'  # 文件路径

with open(file_path, 'rb') as f:
    files = {'file': f}
    response = requests.post(url, files=files)

print(response.text)

在上面的代码中,我们首先定义了目标 URL 和要上传的文件路径。然后,打开文件并使用 requests 库的 post 方法向目标 URL 发送请求,并将文件作为 multipart/form-data 类型的数据发送。最后,打印响应内容。

需要注意的是,如果要上传多个文件,可以将它们放在一个列表中,然后将该列表传递给 files 参数。例如:

import requests

url = 'http://httpbin.org/post'  # 目标 URL
file_paths = ['path/to/file1', 'path/to/file2']  # 文件路径列表

files = []
for file_path in file_paths:
    with open(file_path, 'rb') as f:
        files.append(('file', f))

response = requests.post(url, files=files)

print(response.text)

在这个例子中,我们首先定义了目标 URL 和要上传的文件路径列表。然后,创建一个空列表 files,并遍历文件路径列表,打开每个文件并将其添加到 files 列表中。最后,使用 requests 库的 post 方法向目标 URL 发送请求,并将 files 列表作为 multipart/form-data 类型的数据发送。

Python Requests 库上传文件代码示例

原文地址: http://www.cveoy.top/t/topic/nstW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录