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

在AWS Lambda使用ExcelJS时遭遇Zip文件损坏问题求助

问题原因分析

Lambda环境下出现Zip损坏错误,通常是因为获取的Excel二进制数据存在编码异常、被压缩,或者数据传输过程中被修改导致的。虽然本地和serverless invoke local能正常运行,但Lambda的运行环境(比如Node.js版本、网络请求处理逻辑)和本地存在差异,会影响二进制数据的完整性。

解决方案

  • 强制将响应数据转换为Node.js Buffer
    Lambda中axios返回的arraybuffer可能不是标准的Node.js Buffer类型,ExcelJS加载非Buffer的二进制数据时可能解析失败。可以将响应数据显式转换为Buffer:

    const response = await axios.get(fileUrl, { responseType: 'arraybuffer' });
    // 转换为Buffer
    const excelBuffer = Buffer.from(response.data, 'binary');
    const workbook = new ExcelJS.Workbook();
    await workbook.xlsx.load(excelBuffer);
    
  • 禁止服务器返回压缩内容
    部分服务器会根据请求头返回gzip压缩后的文件,导致axios拿到的是压缩后的二进制数据,而非原始Excel文件。添加Accept-Encoding请求头强制获取原始数据:

    const response = await axios.get(fileUrl, {
      responseType: 'arraybuffer',
      headers: {
        'Accept-Encoding': 'identity' // 禁止压缩
      }
    });
    
  • 确保依赖版本一致
    本地和Lambda部署的ExcelJS、axios版本可能不一致,导致解析逻辑差异。检查package-lock.json或yarn.lock,确保部署时安装的依赖版本和本地测试完全相同。

  • 验证数据完整性
    在Lambda中打印响应数据的长度,和本地请求的长度对比,确认数据没有被截断:

    console.log('Response data length:', response.data.length);
    

    如果长度不一致,说明网络传输中数据丢失,需要检查文件URL的可用性,或者考虑使用S3存储文件后再读取,避免直接通过HTTP请求获取。

修改后的完整代码

async function readExcel(fileUrl) {
  try {
    console.log(fileUrl);
    const response = await axios.get(fileUrl, {
      responseType: 'arraybuffer',
      headers: {
        'Accept-Encoding': 'identity'
      }
    });
    console.log('Response data length:', response.data.length);
    const excelBuffer = Buffer.from(response.data, 'binary');
    const workbook = new ExcelJS.Workbook();
    await workbook.xlsx.load(excelBuffer);
    const data = [];

    const worksheet = workbook.getWorksheet(1);

    worksheet.eachRow((row, rowNumber) => {
      const rowData = {
        LeadName: row.getCell(1).value, 
        MobileNumber: row.getCell(2).value, 
        Email: row.getCell(3).text,
        VehicleRegistrationNumber: row.getCell(4).value,
        City: row.getCell(5).value,
        City_Id: row.getCell(6).value,
        Comments: row.getCell(7).value,
        VehicleModel: row.getCell(8).value,
        AgeGroup: row.getCell(9).value,
        Gender: row.getCell(10).value,
        Destination: row.getCell(11).value,
        Medium: row.getCell(12).value,
        Campaign: row.getCell(13).value,
        LeadSource: row.getCell(14).value
      };
      data.push(rowData);
    });
    data.shift();
    return data;
  } catch (error) {
    console.error('Error reading Excel file:', error);
    throw error;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 00:42:48