如何利用requests上传文件的操作:
测试接口如图:
抓包发现post请求需要传递参数如下:
代码实现如下:需要带上cookies信息,files需要传递文件名称,传递文件的路径以二进制方式传递,文件的格式。
import requests url = "http://admin.cdnzutuan.cn/api/a/upload/uploadappbanner" files = { "file":("蓝天白云.jpg",open(r"D:ico图标文件蓝天白云.jpg","rb"),"image/jpeg") } cookies = {"Cookie": "Cookie: UM_distinctid=170258c85f45d-0918e82b1498a7-2393f61-151800-170258c85f613d; _qddaz=QD.sv7ymv.3dl2m6.k6dsillj; _admin=dHlskxdaUR2vKQZm8rZlQKcuE6KQ6pvXIj6b12d%2BApdNICp5qCFgwkaD93/AjJURkNs7F3yRRzRJUgnBchAh6IeukZrUilucspVI3h7mSY0SNAHZq0TauFDiWbvX6BXPpuePV6nyL%2BnDpFebbHtCEisarA%2B3UpQ8/EP3qxCgSzj95/YRW45zimakG1DpQK3Whi1VmQUlZfHW9BEDd6so9HviWGFDG1A4rIcTse6hrS8%2BcNoIZgZcz7PJUHyyGOJ6j33mKyP0qNIGSPZqfcbaGCh/KUR%2BrPhf8udtg2/6w8nfm38qJ8kDR%2BXCQPA1cm5O; _admin_nick=superadmin"} res = requests.post(url=url,cookies=cookies,files=files) print(res.status_code) print(res.text)
浏览器抓包返回信息如下:
requests接口返回信息如下:
因cookie有效期的问题,封装了一个登录后拿到cookie,再去请求上传文件的接口的方法:
import requests class File_Upload(): def __init__(self): '''登录操作''' self.url = "http://admin.cdnzutuan.cn/api/a/adminuser/login" self.json = { "LoginName": "superadmin", "LoginPwd": "mg123456" } self.headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"} self.res = requests.post(self.url, self.json, self.headers) def uploadFile(self): '''上传文件''' self.url = "http://admin.cdnzutuan.cn/api/a/upload/uploadappbanner" self.files = { "file": ("蓝天白云.jpg", open(r"D:ico图标文件蓝天白云.jpg", "rb"), "image/jpeg") } res = requests.post(url=self.url, cookies=self.res.cookies, files=self.files) print(res.status_code) print(res.text) if __name__ == '__main__': fu = File_Upload() fu.uploadFile()