使用 Python 调用文件上传 API 上传到临时路径示例

基础对接API 使用文档
基础对接API 使用文档
import base64
import json
import os
import os.path
import requests

# 请求基础API地址
API_BASE = 'https://www.example.com/api'
# 请求的API_KEY
ADMIN_API_KEY='xxxxxx'

headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
}

def fileToBase64(file_path):
    with open(file_path, "rb") as file:
        file_content = file.read()
        base64_content = base64.b64encode(file_content).decode('utf-8')
        return base64_content
    return None

def uploadFileTemp(filename):
    content=fileToBase64(filename)
    url = API_BASE + '/admin_api/upload/file_temp'
    data = {
        "ADMIN_API_KEY": ADMIN_API_KEY,
        "filename": filename,
        "base64Content": content
    }
    response = requests.post(url, data=json.dumps(data), headers=headers)
    if response.status_code!=200:
        raise  Exception(f"请求异常:"+data["filename"])
    rsp = response.json()
    if rsp['code']!=0:
        raise  Exception(f"api返回异常:"+rsp)
    return rsp['data']['path']

if __name__ == '__main__':
    # 上传到临时文件
    filePath = '/path/to/txt.txt'
    fileTempPath = uploadFileTemp( filePath )
    print(fileTempPath)
更新: 2024-07-17 13:40:27
QQ
微信
客服