使用Google API Drive v3 Ruby Gem上传文件至共享驱动器遇问题求助
问题分析与解决方案
第一个问题:设置drive_id后仍上传到“My Drive”
你的代码存在三个核心问题:
drive_id参数位置错误:Ruby版Drive API中,drive_id不属于Google::Apis::DriveV3::File对象的属性,必须作为create_file方法的参数传入。- 缺少共享驱动器支持参数:API默认不处理共享驱动器请求,必须添加
supports_all_drives: true参数开启支持。 - 变量定义语法错误:
source_file Tempfile.new("text.txt")是无效语法,需要正确赋值给变量。
修正后的代码:
google_file = Google::Apis::DriveV3::File.new(name: 'test.txt') drive = Google::Apis::DriveV3::DriveService.new # 补充OAuth2授权逻辑(此处需确保已完成身份验证) file = Tempfile.new("text.txt") # 可选:写入测试内容,空文件也可直接上传 file.write("测试内容") file.rewind # 关键参数:drive_id和supports_all_drives需作为create_file的方法参数 drive.create_file(google_file, upload_source: file, drive_id: "123456789", supports_all_drives: true) file.close
第二个问题:设置parents参数报notFound错误
报错核心原因是共享驱动器ID不能直接作为parents的值:parents接收的是文件夹ID(包括共享驱动器的根文件夹ID,但根文件夹ID≠驱动器ID)。
如果需要指定共享驱动器内的文件夹作为父目录,按以下步骤操作:
- 先获取目标文件夹的ID(以共享驱动器的根文件夹为例):
# 获取共享驱动器根文件夹信息 root_folder = drive.list_files( q: "'root' in parents and mimeType='application/vnd.google-apps.folder'", drive_id: "123456789", supports_all_drives: true ).files.first
- 用获取到的文件夹ID作为
parents的值,同时调用create_file时必须添加supports_all_drives: true:
google_file = Google::Apis::DriveV3::File.new( name: 'test.txt', parents: [root_folder.id] ) drive.create_file(google_file, upload_source: file, supports_all_drives: true)
额外注意事项
- 确保授权账号拥有该共享驱动器的读写权限。
- OAuth2授权的scope需包含
https://www.googleapis.com/auth/drive(或对应权限的细分scope)。
内容的提问来源于stack exchange,提问作者sclem72
相关产品推荐
相关产品推荐

