我嘗試從Google Disk上的目錄下載文件。使用google-api-ruby-client從Google Drive下載文件
的代碼,其中大部分來自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>'
但這是它應該按照ruby部分的方式"download files" official tutorial。
我也嘗試過content = service.get_file(file.id, download_dest: "/tmp/#{file.name}")
,但是它失敗的時候出現了相同的一組錯誤。
更新:這是我的發現。如果你開始Google Drive API Ruby quick start tutorial,並要做成下載的東西,
1)的變化範圍,不只是讓你的腳本讀取meatadata,但讀取文件內容,以及:
SCOPE = Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY
至少 SCOPE = Google::Apis::DriveV3::AUTH_DRIVE_READONLY
2)過濾谷歌文檔文件,因爲你不能以這種方式下載它們,你必須轉換它們。要過濾器他們:
2.1)添加mime_type
設置的Fileds:
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
@Nakilon如果我省略'download_dest:...則不會出現錯誤...'和'content'變量似乎是'Google :: Apis :: DriveV3 :: File'類的適當實例。但是,我如何保存文件? 'content.web_content_link'給出'nil'(爲了不過濾字段,我改變了'response = service.list_files(page_size:10)',但它沒有幫助)。 – Mike