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

S3对象解压时出现incorrect header check错误求助

问题原因及解决办法

核心问题分析

1. Lambda解压报错incorrect header check

Lambda代码中错误地将二进制gzip数据流转换为UTF-8字符串:

let data: string = await Body.transformToString();

gzip是二进制格式,并非合法的UTF-8文本,转字符串过程中会破坏原始字节结构,导致解压时无法识别gzip头部,触发"incorrect header check"错误。

2. S3控制台下载文件无法解压

上传代码中设置了Content-Encoding: gzip,这个参数的作用是告诉客户端:内容是经过gzip编码的原始文本,而非独立的gzip压缩包。S3控制台会自动解码该内容,导致你下载到的实际是解压后的JSON文件,但文件名仍保留.gz后缀,直接解压自然会报错。而aws s3 cp默认不自动处理Content-Encoding,所以能下载到原始压缩包,解压正常。


解决办法

修复Lambda解压逻辑

直接处理二进制Buffer,避免转字符串:

const parseResponse = async (resp: GetObjectCommandOutput, rulesCommand: GetObjectCommand): Promise<Config> => {
  const { Body } = resp;
  if (!Body) {
    throw new Error("No body in response");
  }

  let data: string;
  if (rulesCommand.input.Key?.endsWith(".gz")) {
    console.log(`Uncompressing rules file with name ${rulesCommand.input.Key}`);
    try {
      // 直接获取二进制字节数组,转换为Buffer后解压
      const byteArray = await Body.transformToByteArray();
      const buffer = Buffer.from(byteArray);
      data = zlib.gunzipSync(buffer).toString("utf-8");
    } catch (err) {
      throw new Error(`Error decompressing rules file: ${err}`);
    }
  } else {
    // 非压缩文件正常转字符串
    data = await Body.transformToString();
  }

  return JSON.parse(data) as Config;
};

修复S3上传配置

移除Content-Encoding设置,仅保留正确的Content-Type:

let data: string | Buffer = JSON.stringify(rules);
let contentType = "application/json";
let encoding = null;
let filename = `redirector-rules.json`;
if (format === "gz") {
  contentType = "application/gzip";
  // 移除这行:encoding = "gzip";
  filename = `redirector-rules.gz`;
  const buf = Buffer.from(data, "utf-8");
  data = zlib.gzipSync(buf);
}

await s3.upload(filename, data, contentType, encoding);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 02:57:31