python的request库如何写上传
文件的代码?
下面是一个示例代码,演示如何使用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类型的数据发送
原文地址: https://www.cveoy.top/t/topic/chN0 著作权归作者所有。请勿转载和采集!