如何使用服务帐户从 google 驱动器 api 下载文件?

How to download file from google drive api with service account?

你好google黑客!

我正在使用 Drive Service 应用程序并像这样成功上传文件:

require 'googleauth'
require 'google/apis/drive_v2'

Drive = Google::Apis::DriveV2

upload_source = "/User/my_user_name/hacking.txt"
drive = Drive::DriveService.new
# Drive::AUTH_DRIVE is equal to https://www.googleapis.com/auth/drive
drive.authorization = Google::Auth.get_application_default([Drive::AUTH_DRIVE])
file = drive.insert_file({title: 'hacking.txt'}, upload_source: upload_source)

file 有很多属性,像这样: download_url

但是当我尝试在浏览器中打开此 download_url 时,它显示空白屏幕。为什么我下载不了?

我猜,可能是权限问题?但是范围是正确的,上传成功了...

答案很简单 - 我们不能从 file 对象下载它,我们必须发送另一个 get 请求,就像这样下载它:

drive.get_file(file.id, download_dest: '/tmp/my_file.txt')