【发布时间】:2016-09-23 20:50:20
【问题描述】:
我尝试从 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"
【问题讨论】:
-
如果没有
download_dest:参数,你会得到同样的错误吗? -
@Nakilon 如果我省略
download_dest: ...,它不会出错,并且content变量似乎是Google::Apis::DriveV3::File类的正确实例。但是如何保存文件?content.web_content_link提供nil(我更改了response = service.list_files(page_size: 10)以便不过滤字段,但它没有帮助)。
标签: google-drive-api google-api-ruby-client