代码示例1
r = requests.post(
url='http://upload.renren.com/upload.fcgi?pagetype=addpublishersingle&hostid=967004081&'
'callback=window.parent.handlePhotoData&uploadid=profile_publisher_photo_1540215890321',
data=uploadData(),
headers={
'Conteny-Type': 'multipart/form-data'},
files={
"file": ("wx.jpg", open("c:/wx.jpg", "rb"), "image/jpeg", {
})},
cookies=login())
print(r.status_code)
print(r.text)
代码示例2
#coding:utf-8
import requests
import os
def read_images():
# 指定路径
path = r"./photo"
#得到文件夹下的所有文件名称
files_name = os.listdir(path)
print(files_name)
#接口地址
url = "http://******.vip/common/api/upload/image"
headers = {
'Conteny-Type': 'multipart/form-data'}
#图片上传初始计数
num=0
# 循环遍历该目录下所有图片
for file in files_name:
body={
# 参数rb,以二进制格式打开一个文件用于只读
'file':("file",open("./photo/"+file,"rb"),"image/png/jpg")
}
#上传图片
r = requests.post(url,files=body,headers=headers)
print(r.text)
print(r.status_code)
num=num+1
if num == 2:
break
print('-------------上传结束---------共上传', num, '张图片------------------')
# print(r.text)
if __name__ == "__main__":
read_images()
服务器需要返回地址的,一般要有切割分隔符标志multipart/form-data; boundary,服务器才知道从那里切割并返回
代码示例:
from urllib3 import encode_multipart_formdata
with open(img_path + img_name, mode="rb")as f: # 打开文件
file = {
"filedata": (img_name, f.read()) # 引号的file是接口的字段,后面的是文件的名称、文件的内容
}
encode_data = encode_multipart_formdata(file)
file_data = encode_data[0]
print(encode_data[1])
print(file_data)
headers['Content-Type']=encode_data[1]
p = requests.post(url=url,data=file_data,headers=headers,cookies=cookies,verify=False)
引用:
Python接口自动化测试之文件上传.
post 提交之 multipart/form-data; boundary= ….
python上传图片到服务器,获取URL的坑.
xhr multipart boundary分隔符.