使用ruby客户端从谷歌云存储下载文件获取HTTP重定向

时间:2013-08-12 21:41:55

标签: google-cloud-storage

我正在尝试使用Ruby客户端和服务帐户授权从GCS下载文件;这是我的代码:

def build_client
  client = Google::APIClient.new()
  key = Google::APIClient::PKCS12.load_key(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'notasecret')
  service_account = Google::APIClient::JWTAsserter.new(
      SERVICE_ACCOUNT_EMAIL,
      'https://www.googleapis.com/auth/devstorage.full_control',
  key)
  client.authorization = service_account.authorize
  client
end

client = build_client
storage = client.discovered_api('storage', 'v1beta2')

#Get (download) a specific object from a bucket
bucket_get_result = client.execute(
    api_method: storage.objects.get,
    parameters: {bucket: BUCKET, object: params[:file_name], alt: 'media'}
)
puts bucket_get_result.body

结果正文是一个重定向细节,如下所示:

<HTML>
<HEAD>
<TITLE>Temporary Redirect</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Temporary Redirect</H1>
The document has moved <A     HREF="https://storage.googleapis.com/my_bucket_name/my_file_name">here</A>.
</BODY>
</HTML>

...然后,如果我尝试转到重定向“位置”,我会收到一个未经授权的HTTP。那么,如何使用ruby客户端从GCS下载文件? https://developers.google.com/storage/docs/json_api/v1/objects/get说:

  

如果您提供URL参数alt = media,那么它将使用响应正文中的对象数据进行响应

1 个答案:

答案 0 :(得分:4)

Google Ruby API客户端目前不支持下载媒体。

但是,你可以自己完成剩下的工作。

require 'httparty'

get_result = bucket_get_result = client.execute(
    api_method: storage.objects.get,
    parameters: {bucket: BUCKET, object: params[:file_name], :alt=>'media'})
url = get_result.response.env[:response_headers]['location']
token = "Bearer #{bucket_get_result.request.authorization.access_token}"
puts HTTParty.get(url, :headers => {"Authorization" => token}).body