使用 google-api-ruby-client 从 Google 驱动器下载文件

Download a file from Google Drive using google-api-ruby-client

我尝试从 Google 磁盘上的目录下载文件。

代码,主要是从 official quickstart guide 复制的,工作正常:

# ... code from official quickstart tutorial...

# Initialize the API
service = Google::Apis::DriveV3::DriveService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize


# now the real deal
response = service.list_files(q: "'0ByJUN4GMe_2jODVJVVpmRE1VTDg' in parents and trashed != true",
                              page_size: 100,
                              fields: 'nextPageToken, files(id, name)')
puts 'Files:'
puts 'No files found' if response.files.empty?
response.files.each do |file|
  puts "#{file.name} (#{file.id})"
  # content = service.get_file(file.id, download_dest: StringIO.new)
end

输出看起来不错:

Files:
k.h264 (0B4D93ILRdf51Sk40UzBoYmZKMTQ)
output_file.h264 (0B4D93ILRdf51V1RGUDFIWFQ5cG8)
test.mp4 (0B4D93ILRdf51dWpoZWdBV3l4WjQ)
test2.mp4 (0B4D93ILRdf51ZmN4ZGlwZjBvR2M)
test3.mp4 (0B4D93ILRdf51ZXo0WnVfdVBjTlk)
12.mp4 (0ByJUN4GMe_2jRzEwS1FWTnVkX00)
01.mp4 (0ByJUN4GMe_2jSlRWVEw4a1gxa2s)
01.mp4 (0ByJUN4GMe_2jOFpPMW9YNjJuY2M)

但是一旦我取消注释 content = service.get_file(file.id, download_dest: StringIO.new),我就会得到很多错误:

Files:
k.h264 (0B4D93ILRdf51Sk40UzBoYmZKMTQ)
/Users/mvasin/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/google-api-client-0.9.15/lib/google/apis/core/http_command.rb:211:in `check_status': Invalid request (Google::Apis::ClientError)
[...lots of other 'from' stuff...]
from /Users/mvasin/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/google-api-client-0.9.15/generated/google/apis/drive_v3/service.rb:772:in `get_file'
from quickstart.rb:56:in `block in <main>'
from quickstart.rb:54:in `each'
from quickstart.rb:54:in `<main>'

但根据 "download files" official tutorial 中的 ruby 部分,它应该是这样工作的。

我也试过 content = service.get_file(file.id, download_dest: "/tmp/#{file.name}"),但失败了,出现了同样的错误。

更新:这是我的发现。 如果您从 Google Drive API Ruby quick start tutorial 开始,并想让它下载一些东西,

1) 更改范围,不仅让您的脚本读取元数据,还读取文件内容:

SCOPE = Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY 至少 SCOPE = Google::Apis::DriveV3::AUTH_DRIVE_READONLY

2) 过滤掉google个docs文件,因为这样下载不了,必须要转换。归档它们:

2.1) 将 mime_type 添加到文件集中:

response = service.list_files(page_size: 10, fields: 'nextPageToken, files(id, name, mime_type)')

2.2) 并在打印文件 ID 和名称的最后一个循环中,输入类似

的内容

service.get_file(file.id, download_dest: "/your/path/#{file.name}") unless file.mime_type.include? "application/vnd.google-apps"

从您收到的错误信息来看,您的请求无效。所以请确保您的请求是正确的。这里是 documentation 如何使用 Ruby 下载文件(只需单击示例中的 Ruby 即可查看 ruby 代码。)

Take NOTE: Downloading the file requires the user to have at least read access. Additionally, your app must be authorized with a scope that allows reading of file content.

有关更多信息,请查看这些线程: