You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Newman调用中集成Postman发送下载功能并保存二进制响应?

刚好之前处理过类似的需求,Newman作为命令行工具,默认确实不会帮你处理二进制响应的可视化和保存,但我们可以通过Postman脚本+Newman的命令行参数/Node.js API来搞定,下面给你两种实用的方案:

方法一:Postman测试脚本+Newman命令行分步实现

这种方法适合不想写复杂Node脚本的场景,先在Postman里配置好响应处理逻辑,再用Newman导出数据后保存文件:

1. 在Postman中添加测试脚本

打开你的请求,切换到Tests标签,添加这段代码:

// 检查响应是否为二进制类型(比如图片、通用二进制流)
const contentType = pm.response.headers.get('Content-Type');
if (contentType.includes('image/') || contentType === 'application/octet-stream') {
    // 将二进制响应转为Base64格式,方便存入环境变量
    const base64Response = pm.response.stream.toString('base64');
    pm.environment.set('binaryResponse', base64Response);

    // 尝试从响应头中提取文件名(如果接口返回Content-Disposition的话)
    const contentDisposition = pm.response.headers.get('Content-Disposition');
    let outputFilename = 'default-output.png'; // 默认文件名
    if (contentDisposition) {
        const filenameMatch = contentDisposition.match(/filename="?([^"]+)"?/);
        if (filenameMatch) outputFilename = filenameMatch[1];
    }
    pm.environment.set('outputFilename', outputFilename);
}

2. 用Newman运行集合并导出环境变量

在命令行执行以下命令,运行你的集合并把包含二进制数据的环境变量导出:

newman run your-collection.json --environment your-env.json --export-environment post-run-env.json

3. 编写脚本将Base64转为文件

创建一个简单的Node.js脚本save-binary.js:

const fs = require('fs');

// 读取Newman导出的环境变量文件
const envData = JSON.parse(fs.readFileSync('post-run-env.json', 'utf8'));

// 从环境变量中提取数据
const base64Data = envData.values.find(item => item.key === 'binaryResponse').value;
const filename = envData.values.find(item => item.key === 'outputFilename').value;

// 解码Base64并写入本地文件
fs.writeFileSync(filename, Buffer.from(base64Data, 'base64'));
console.log(`✅ 文件已成功保存:${filename}`);

然后运行这个脚本:

node save-binary.js
方法二:用Newman Node.js API一键实现(更高效)

如果想一步到位,直接用Newman的Node.js API编写脚本,运行集合时自动处理并保存二进制响应:

创建run-and-save.js脚本:

const newman = require('newman');
const fs = require('fs');

newman.run({
    collection: require('./your-collection.json'), // 本地集合文件,也可以用集合URL
    environment: require('./your-env.json'), // 你的环境变量文件
    reporters: 'cli' // 保留命令行的运行日志输出
})
// 监听请求完成事件
.on('request', (err, args) => {
    if (!err) {
        const response = args.response;
        const contentType = response.headers.get('Content-Type');
        
        // 判断是否为需要保存的二进制响应
        if (contentType.includes('image/') || contentType === 'application/octet-stream') {
            // 确定输出文件名
            let filename = 'default-output.png';
            const contentDisposition = response.headers.get('Content-Disposition');
            if (contentDisposition) {
                const filenameMatch = contentDisposition.match(/filename="?([^"]+)"?/);
                if (filenameMatch) filename = filenameMatch[1];
            }

            // 直接将二进制响应流写入文件
            fs.writeFileSync(filename, response.stream);
            console.log(`✅ 二进制响应已保存至:${filename}`);
        }
    }
})
// 监听集合运行完成事件
.on('done', (err, summary) => {
    if (err) {
        console.error('❌ 集合运行失败:', err);
    } else {
        console.log('\n✅ 所有请求运行完成!');
    }
});

运行这个脚本即可:

node run-and-save.js
关于Newman中查看二进制响应的说明

Newman是纯命令行工具,没办法像Postman那样直接在界面里预览图片或二进制文件,但你可以:

  • 用上面的方法保存文件后,直接打开本地文件查看内容
  • 在Postman的测试脚本中添加日志,输出响应的基本信息(比如大小、类型):
console.log(`📦 二进制响应大小:${pm.response.stream.length} bytes`);
console.log(`📋 Content-Type:${pm.response.headers.get('Content-Type')}`);
模拟Postman的「发送并下载」功能

Postman的「发送并下载」本质就是将响应的二进制内容直接保存到本地,上面两种方案都完美实现了这个逻辑——请求完成后自动把二进制响应写入指定文件,和Postman的原生功能效果一致。

内容的提问来源于stack exchange,提问作者Ulysses

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:06:10