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

能否通过stub和predicate让Mountebank模拟GET请求返回octet-stream图片?

Mountebank返回octet-stream格式图片的解决方案

失败原因

原文本文件配置中使用的stringify模板函数仅支持文本内容解析,读取图片等二进制文件时会强制进行UTF-8编码转换,触发编码错误导致Mountebank启动失败。

可行配置方案

无需修改原有predicate匹配规则,仅调整responses部分配置即可实现二进制图片返回,以下提供两种常用实现方式:

方式1:使用inject动态读取本地图片文件(推荐)

无需提前转码,直接通过注入JS脚本读取本地二进制文件返回:

{
  "responses": [
    {
      "inject": "<%- stringify(filename, 'scripts/return-image.js') %>"
    }
  ],
  "predicates": [
    {
      "and": [
        {
          "equals": {
            "method": "GET",
            "path": "/resources/4df3dab6-003b-440d"
          }
        }            
      ]
    }
  ]
}

对应scripts/return-image.js内容:

const fs = require('fs');
const path = require('path');
// 替换为你的实际图片路径
const imagePath = path.join(__dirname, '../templates/attachments/sample_image.png');
const imageBuffer = fs.readFileSync(imagePath);

return {
  statusCode: 200,
  headers: {
    'Content-Type': 'application/octet-stream',
    'Content-Disposition': 'attachment; filename=sample_image.png'
  },
  body: imageBuffer.toString('base64'),
  mode: 'binary'
};

方式2:直接硬编码base64到配置文件

如果图片固定不需要经常修改,可以把图片转成base64编码后直接写入配置:

{
  "responses": [
    {
      "is": {
        "headers": {
          "content-disposition": "attachment; filename=sample_image.png",
          "content-type": "application/octet-stream"
        },
        "statusCode": 200,
        "mode": "binary",
        "body":  "此处替换为图片文件的base64编码字符串"
      }
    }
  ],
  "predicates": [
    {
      "and": [
        {
          "equals": {
            "method": "GET",
            "path": "/resources/4df3dab6-003b-440d"
          }
        }            
      ]
    }
  ]
}

注意事项

  • 所有文件路径都要和Mountebank启动时的工作目录对应,避免出现文件找不到的错误
  • 二进制响应必须加"mode": "binary"配置,否则Mountebank会把body内容当做普通文本处理导致图片损坏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 01:45:00