Python接口自動化——文件上傳/下載接口

〇、前言
文件上傳/下載接口與普通接口類似,但是有細微的區別。
如果需要發送文件到服務器,例如:上傳文檔、圖片、視頻等,就需要發送二進制數據,上傳文件一般使用的都是 Content-Type: multipart/form-data 數據類型,可以發送文件,也可以發送相關的消息體數據。
反之,文件下載就是將二進制格式的響應內容存儲到本地,並根據需要下載的文件的格式來寫文件名,例如:F:/合同文件.pdf。
一、文件上傳接口
1. 接口文檔
Request URL: /createbyfile
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": ( "", # 元組第一個值為文件名稱,沒有則取None open(r"F:\pdf_file.pdf", "rb"), # 若第一個值非None,則取文件open打開的二進制流,否則直接寫文件路徑,如"F:\pdf_file.pdf" "pdf" # 文件類型 )"file": ( None, "F:\pdf_file.pdf" ) -
構造其他數據
{ "title": "接口發起的文檔", "fileType": "pdf" } -
發送請求,將文件數據以
files參數傳入,其他消息體數據通過data、json、headers、cookies等傳入req = { "url": "127.0.0.1/v2/document/createbyfile", "method": "POST", "headers": {}, "files": {"file": ("", open(r"F:\pdf_file.pdf", "rb"), "pdf")}, "data": { "title": "接口發起的文檔", "fileType": "pdf" } }
(2)完整代碼
base_api.py
import requests
class BaseApi:
@staticmethod
def requests_http(req):
# ** 解包
result = requests.request(**req)
return result
api/createbyfile.py
# -*- coding:utf-8 -*-
# 作者:IT小學生蔡坨坨
# 時間:2022/3/12 21:04
# 功能:根據文件類型創建合同文檔
from base_api import BaseApi
class Createbyfile:
def createbyfile(self):
req = {
"url": "127.0.0.1/createbyfile",
"method": "POST",
"headers": {},
"files": {"file": ("", open(r"F:\pdf_file.pdf", "rb"), "pdf")},
"data": {
"title": "接口發起的文檔",
"fileType": "pdf"
}
}
res = BaseApi().requests_http(req)
assert res.status_code == 200
res_json = res.json()
return res_json["result"]["documentId"]
if __name__ == '__main__':
Createbyfile().createbyfile()
二、文件下載接口
1. 接口文檔
Request URL:/download
Request Method:GET
| 名稱 | 類型 | 是否必須 | 描述 |
|---|---|---|---|
| contractId | Long | ID | ID |
| downloadItems | String[] | 否 | 下載可選項,NORMAL(正文),ATTACHMENT(附件) |
| needCompressForOneFile | Boolean | 是,默認單文件也壓縮 | 當下載的文件僅一份時,是否壓縮 |
2. 代碼實現
# -*- coding:utf-8 -*-
# 作者:IT小學生蔡坨坨
# 時間:2022/4/5 2:56
# 功能:下載合同
from base_api import BaseApi
class Download:
def download(self):
req = {
"url": "127.0.0.1/download",
"method": "GET",
"headers": {},
"params": {
"contractId": 2947403075747869536,
"downloadItems": ["NORMAL"],
"needCompressForOneFile": False
},
}
res = BaseApi().requests_http(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()



