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

Google Drive API报Internal Error:App Script文件创建更新问题求助

Google Apps Script中Drive文件创建/更新因Blob引发Internal Error的解决建议

问题背景

此前长期正常运行的代码近期开始返回Internal Error,经排查确认问题由Blob相关代码引发,推测与Utilities函数变更有关。原代码如下:

var resource =
{
  title: 'file name',
  mimeType: 'application/vnd.google-apps.spreadsheet',
  parents: [{ id: parentFolderId }]
};

var blob = Utilities.newBlob(Utilities.base64Decode(base64String)) //issue occurs due to blob
//if file already exists, we are updating the file.
if (fileExists) {
    Drive.Files.update(resource, fileId, blob);
}
else {
    Drive.Files.insert(resource, blob);
}

可能原因分析

  1. Blob未指定MIME类型:Utilities.newBlob未显式设置源文件的MIME类型,导致Drive API无法正确解析并转换为Google表格格式,近期API可能收紧了类型校验。
  2. Base64字符串无效:输入的base64String存在格式问题(如多余换行、截断、非标准字符),导致解码后的数据损坏。
  3. Drive API v2兼容性问题:Drive API v2已进入维护阶段,部分接口行为可能发生变更,引发模糊的内部错误。

解决方案与替代方案

1. 显式指定Blob的源文件MIME类型

创建Google表格时,Blob需对应原始文件的MIME类型(而非Google表格的MIME类型),例如CSV文件用text/csv,Excel文件用application/vnd.openxmlformats-officedocument.spreadsheetml.sheet。修改Blob创建代码:

// 示例:假设源文件是CSV格式
var decodedData = Utilities.base64Decode(base64String);
var blob = Utilities.newBlob(decodedData, "text/csv", "temp.csv");

这样Drive API能明确识别源文件类型,正确转换为Google表格。

2. 校验Base64解码过程

添加异常捕获,定位解码过程中的错误:

var decodedData;
try {
  decodedData = Utilities.base64Decode(base64String);
} catch (e) {
  console.error("Base64解码失败:", e.message);
  throw new Error("无效的Base64字符串,请检查输入");
}
var blob = Utilities.newBlob(decodedData, "text/csv");

3. 迁移至Drive API v3

Drive API v3是当前推荐版本,接口行为更稳定。需先在App Script编辑器的扩展 > 应用脚本API > 高级Google服务中启用Drive API v3,然后修改代码:

// 创建文件(v3)
var resource = {
  name: 'file name', // 替换v2的title为name
  mimeType: 'application/vnd.google-apps.spreadsheet',
  parents: [parentFolderId] // 直接传入文件夹ID数组
};
if (fileExists) {
  // 更新文件
  Drive.Files.update(resource, fileId, blob, {convert: true});
} else {
  // 创建文件,指定convert参数确保转换为Google表格
  Drive.Files.create(resource, blob, {convert: true});
}

4. 检查权限与API配额

  • 确认脚本已获得https://www.googleapis.com/auth/drive的完整权限(而非只读权限)。
  • 查看Google Cloud控制台中Drive API的配额使用情况,避免因配额耗尽引发错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 06:41:19