轉載請注明出處❤️
作者:測試蔡坨坨
原文鏈接:caituotuo.top/9cf3344.html
你好,我是測試蔡坨坨。
我們在做接口自動化測試的時候,經常會碰到文件上傳接口
和文件下載接口
。
那么,文件接口跟普通接口有什么區別呢?又該如何實現呢?
〇、前言
文件上傳/下載接口
與普通接口
類似,但是有細微的區別。
如果需要發送文件到服務器,例如:上傳文檔、圖片、視頻等,就需要發送二進制數據,上傳文件一般使用的都是 Content-Type: multipart/form-data
數據類型,可以發送文件,也可以發送相關的消息體數據。
反之,文件下載就是將二進制格式的響應內容存儲到本地,並根據需要下載的文件格式來寫文件名,例如:F:/caituotuo-file.pdf。
一、文件上傳接口
1. 接口文檔
Request URL: /createfile
Request Method: POST
Content-Type: multipart/form-data
名稱 | 類型 | 是否必須 | 描述 |
---|---|---|---|
file | File | 是 | 文件 |
title | String | 是 | 文件名稱 |
fileType | String | 是 | 文件類型:doc, docx, txt, pdf, png, gif, jpg, jpeg, tiff, html, rtf, xls, txt |
2. 代碼實現
(1)實現步驟:
-
構造文件數據,通過open()函數以二進制方式打開文件
文件上傳接口參數與普通post請求一樣,需要寫成Key和Value模式,Key為參數名稱file(也是組件的name屬性),Value為一個元組(與普通接口不同的地方)
"file": ( "caituotuo-file.pdf", # 元組第一個值為文件名稱,沒有則取None open(r"F:\caituotuo-file.pdf", "rb"), # 若第一個值非None,則取文件open打開的二進制流,否則直接寫文件路徑,如"F:\caituotuo-file.pdf" "pdf" # 文件類型 )
"file": ( None, "F:\caituotuo-file.pdf" )
-
構造其他數據
{ "title": "接口上傳的文件", "fileType": "pdf" }
-
發送請求,將文件數據以
files
參數傳入,其他消息體數據通過data
、headers
、cookies
等傳入req = { "url": "127.0.0.1/createfile", "method": "POST", "headers": {}, "files": {"file": ("caituotuo-file.pdf", open(r"F:\caituotuo-file.pdf", "rb"), "pdf")}, "data": { "title": "接口上傳的文件", "fileType": "pdf" } }
(2)完整代碼
# -*- coding:utf-8 -*-
# 作者:測試蔡坨坨
# 時間:2022/3/12 21:04
# 功能:上傳文件demo
import requests
class Createfile:
def createfile(self):
req = {
"url": "127.0.0.1/createfile",
"method": "POST",
"headers": {},
"files": {"file": ("", open(r"F:\caituotuo-file.pdf", "rb"), "pdf")},
"data": {
"title": "接口上傳的文件",
"fileType": "pdf"
}
}
res = requests.request(**req)
assert res.status_code == 200
res_json = res.json()
return res_json["result"]["id"]
if __name__ == '__main__':
Createfile().createfile()
二、文件下載接口
1. 接口文檔
Request URL:/download
Request Method:GET
名稱 | 類型 | 是否必須 | 描述 |
---|---|---|---|
id | Long | 是 | 文件組id |
downloadItems | String[] | 否 | 下載可選項 |
needCompressForOneFile | Boolean | 是,默認單文件也壓縮 | 當下載的文件僅一份時,是否壓縮 |
2. 代碼實現
# -*- coding:utf-8 -*-
# 作者:測試蔡坨坨
# 時間:2022/4/5 2:56
# 功能:下載文件demo
import requests
class Download:
def download(self):
req = {
"url": "127.0.0.1/download",
"method": "GET",
"headers": {},
"params": {
"id": 2947403045981869536,
"downloadItems": ["NORMAL"],
"needCompressForOneFile": False
},
}
res = requests.request(**req).content # 注意“.content"獲取返回內容
# with open("F:/response.zip", "wb") as f: # 多份文件返回壓縮包
with open("F:/response.pdf", "wb") as f:
f.write(res)
return res
if __name__ == '__main__':
Download().download()