接口测试时如何上传文件(图片、安装包等)

在做接口测试时,针对需要上传文件(图片、安装包等)的 POST 请求,一般都是通过 HTTP 的 multipart/form-data 方式来传输。下面分别介绍在 Postman 和 Python(requests 库)里如何实现。

一、Postman 中上传文件

1. 选择请求方法和 URL

  • Method 选 "POST"(或接口文档指定的方法)
  • 在地址栏填入接口 URL

    2. 设置 Body 为 form‑data
  • 点击 "Body" 标签
  • 选中 "form‑data" 选项

    3. 新增字段并设置类型为 File
  • 在 Key 列输入字段名(与后台约定一致)
  • 下拉选择 "File",Value 列会出现文件选择按钮
    4. 如果还有其他普通文本参数,继续在 form‑data 中以 Text 类型添加即可。

5. 添加对应的请求参数,并发送请求

  • 点击 "Send"
  • 查看返回,确认文件是否上传成功

二、Python(requests)自动化脚本

使用 requests 库发送 multipart/form-data 请求:

python 复制代码
import requests

def upload_file(api_url, params, file_paths):
    """
    api_url: 接口地址
    params: dict, 普通表单字段
    file_paths: dict, 文件字段名 -> 本地文件路径
    """
    # 构造 files 参数
    files = {}
    for field_name, path in file_paths.items():
        # 'rb' 以二进制模式打开文件
        files[field_name] = open(path, 'rb')

    try:
        response = requests.post(api_url, data=params, files=files)
        response.raise_for_status()  # 如果返回码不是200-399,会抛出异常
        return response.json()
    finally:
        # 关闭文件句柄
        for f in files.values():
            f.close()

if __name__ == "__main__":
    api_url = "https://api.example.com/upload"
    params = {
        "username": "test_user",
        "description": "这是一个测试上传"
    }
    file_paths = {
        "image": "path/to/logo.png",
        "installer": "path/to/app.apk"
    }

    result = upload_file(api_url, params, file_paths)
    print("接口返回:", result)
  • data=params:普通文本字段
  • files=files:文件字段,requests 会自动将 Content-Type 设置为 multipart/form-data
  • 调用时,只需将文件路径和字段名对应好即可

三、在测试框架(pytest/unittest)中集成

如果使用 pytest 进行自动化,可以这样写:

python 复制代码
import pytest
import requests

@pytest.fixture
def api_url():
    return "https://api.example.com/upload"

@pytest.fixture
def common_params():
    return {
        "username": "pytest_user",
        "description": "pytest 上传测试"
    }

def test_upload(api_url, common_params):
    files = {
        "image": open("tests/data/logo.png", "rb"),
        "installer": open("tests/data/app.apk", "rb"),
    }
    resp = requests.post(api_url, data=common_params, files=files)
    for f in files.values(): f.close()

    assert resp.status_code == 200
    json_body = resp.json()
    # 根据接口文档断言
    assert json_body.get("success") is True
    assert "fileUrl" in json_body
  • 用 pytest.fixture 分离公共配置
  • 在测试函数里直接调用 requests.post
  • 断言 HTTP 状态码和返回字段

注意点

  • 超大文件 :若文件非常大,考虑分片上传或流式上传,详见 requests 的 stream 机制。

  • 自定义 Headers :如果需要授权(如 Bearer Token),可在请求中加入

    python 复制代码
    headers={"Authorization": "Bearer xxx"}
  • 超时与重试:生产脚本中建议加上 timeout=(连接超时, 读取超时),并结合 requests.adapters.HTTPAdapter 实现重试。

相关推荐
Juchecar2 小时前
分析:将现代开源浏览器的JavaScript引擎更换为Python的可行性与操作
前端·javascript·python
科大饭桶2 小时前
昇腾AI自学Day2-- 深度学习基础工具与数学
人工智能·pytorch·python·深度学习·numpy
天才测试猿4 小时前
常见的Jmeter压测问题
自动化测试·软件测试·python·测试工具·jmeter·职场和发展·压力测试
mortimer4 小时前
一次与“顽固”外部程序的艰难交锋:subprocess 调用exe踩坑实录
windows·python·ai编程
来自天蝎座的孙孙5 小时前
洛谷P1595讲解(加强版)+错排讲解
python·算法
张子夜 iiii6 小时前
机器学习算法系列专栏:主成分分析(PCA)降维算法(初学者)
人工智能·python·算法·机器学习
跟橙姐学代码7 小时前
学Python像学做人:从基础语法到人生哲理的成长之路
前端·python
Keying,,,,7 小时前
力扣hot100 | 矩阵 | 73. 矩阵置零、54. 螺旋矩阵、48. 旋转图像、240. 搜索二维矩阵 II
python·算法·leetcode·矩阵
桃源学社(接毕设)8 小时前
基于人工智能和物联网融合跌倒监控系统(LW+源码+讲解+部署)
人工智能·python·单片机·yolov8
yunhuibin8 小时前
pycharm2025导入anaconda创建的各个AI环境
人工智能·python