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

使用Google Drive API上传文件生成0字节文件的问题求助

Google Drive API 多部分上传文件显示0字节问题解决

问题重现

按照Google Drive API多部分上传的Node.js示例适配代码后,文件能在指定共享驱动器目录中创建(文件名、类型正确),但文件大小始终为0字节。尝试过fs.createReadStream、fs.readFileSync、Base64编码等方式,仅纯文本内容能正常上传,文件夹创建功能正常。

可能原因及解决方案

1. 文件路径/权限验证

首先确认目标文件存在且Node进程拥有读取权限:

const filePath = path.join('/Users/john/Documents/cat.jpg');

// 检查文件是否存在
if (!fs.existsSync(filePath)) {
  throw new Error(`目标文件不存在: ${filePath}`);
}

// 检查读取权限
try {
  fs.accessSync(filePath, fs.constants.R_OK);
} catch (err) {
  throw new Error(`无文件读取权限: ${filePath}`);
}

2. 显式指定上传类型

虽然多部分上传是默认行为,但显式设置uploadType: 'multipart'可避免潜在的库逻辑问题:

await this.drive.files.create({
  auth: this.jwtCreds,
  supportsAllDrives: true,
  requestBody: requestBody,
  media: media,
  uploadType: 'multipart' // 显式声明上传类型
});

3. 正确传递文件内容

方式一:使用ReadStream并监听错误

给流添加错误监听,排查读取过程中的潜在问题:

const fileStream = fs.createReadStream(filePath);
fileStream.on('error', (err) => {
  this.logger.error(`文件流读取失败: ${err.message}`);
  throw err;
});

const media = {
  mimeType: 'image/jpeg',
  body: fileStream
};

方式二:使用原始Buffer

使用fs.readFileSync时不要指定编码,确保传递的是原始二进制Buffer:

const media = {
  mimeType: 'image/jpeg',
  body: fs.readFileSync(filePath) // 无编码参数,返回原始Buffer
};

4. 更新googleapis库版本

旧版本的googleapis可能存在流处理或多部分上传的bug,更新到最新版本:

npm update googleapis

5. 验证JWT认证初始化

确保this.jwtCreds已完成授权流程,避免因未授权导致的上传中断:

// JWT初始化示例
const { google } = require('googleapis');

const jwt = new google.auth.JWT(
  '<你的客户端邮箱>',
  null,
  '<你的私钥内容>',
  ['https://www.googleapis.com/auth/drive']
);

// 提前完成授权
await jwt.authorize();
this.jwtCreds = jwt;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 13:22:12