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

Google Apps Script中getAllBlobs()废弃致附件损坏的问题求解

问题分析与解决方案

问题根源

  1. 废弃方法引发异常:getAllBlobs()已被Google Apps Script废弃,调用该方法会导致Zip文件处理逻辑异常,最终生成损坏的附件。
  2. 冗余双层压缩破坏结构:原代码先将文件打包为AnexoContasAPagar.zip,再通过getAllBlobs()错误提取内部Blob后二次打包为Anexo.zip,这种嵌套压缩逻辑无意义且会破坏文件结构。
  3. 无效冗余代码:原代码中获取file数组的循环完全未被使用,属于无效代码。

修正后的代码

方案1:直接生成单一层级Zip附件(推荐)

如果不需要双层Zip结构,直接将所有文件打包为最终附件即可:

function getAttachmentArchive(){
  const totalRange = retriveTotalSubmission();
  const sheet = SpreadsheetApp.openById('1Jf3ikldJoPgaVK-l5Gpo8YFjPmI4q2a2Rq9txNT3g');
  const attachmentArchive = sheet.getRange(`X${totalRange + 1}`);
  
  const folderUrls = attachmentArchive.getValue().split(',');
  let filesBlob = [];

  for(let i = 0; i < folderUrls.length; i++){
    const url = folderUrls[i].trim();
    const fetchedBlob = UrlFetchApp.fetch(url).getBlob();
    const fileId = url.split('=')[1];
    
    // 设置Blob名称为原文件名
    fetchedBlob.setName(DriveApp.getFileById(fileId).getName());
    filesBlob.push(fetchedBlob);
  }

  // 直接打包所有文件为目标Zip
  const anexo = Utilities.zip(filesBlob, 'AnexoContasAPagar.zip');
  const attachmentBase64 = Utilities.base64Encode(anexo.getBytes());
  
  return attachmentBase64;
}

方案2:保留双层Zip结构(若业务需要)

如果必须先将文件打包为AnexoContasAPagar.zip,再嵌套进Anexo.zip,需将内层Zip的Blob作为单个元素传入二次压缩:

function getAttachmentArchive(){
  const totalRange = retriveTotalSubmission();
  const sheet = SpreadsheetApp.openById('1Jf3ikldJoPgaVK-l5Gpo8YFjPmI4q2a2Rq9txNT3g');
  const attachmentArchive = sheet.getRange(`X${totalRange + 1}`);
  
  const folderUrls = attachmentArchive.getValue().split(',');
  let filesBlob = [];

  for(let i = 0; i < folderUrls.length; i++){
    const url = folderUrls[i].trim();
    const fetchedBlob = UrlFetchApp.fetch(url).getBlob();
    const fileId = url.split('=')[1];
    
    fetchedBlob.setName(DriveApp.getFileById(fileId).getName());
    filesBlob.push(fetchedBlob);
  }

  // 先生成内层Zip
  const innerZipBlob = Utilities.zip(filesBlob, 'AnexoContasAPagar.zip');
  // 将内层Zip作为单个文件打包为外层Zip
  const anexo = Utilities.zip([innerZipBlob], 'Anexo.zip');
  
  const attachmentBase64 = Utilities.base64Encode(anexo.getBytes());
  return attachmentBase64;
}

关键修改点

  • 移除废弃的getAllBlobs()方法,直接使用Utilities.zip()返回的Blob对象。
  • 删除未使用的fileId数组及对应DriveApp文件获取循环,简化逻辑。
  • 修复循环变量未声明的问题(原代码i未用let声明,会导致全局变量污染)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:15:24