簡體   English   中英

使用google-api-php-client下載文件

[英]Downloading files using google-api-php-client

我在嘗試使用https://code.google.com/p/google-api-php-client/上的php客戶端從Google雲端存儲下載文件時遇到問題

我已經驗證了自己的確定並使用以下代碼我可以返回一個包含我的文件的鏈接的對象

$this->storageService = new Google_StorageService($this->client);
$this->objects = $this->storageService->objects;

$options = array(
    'prefix' => 'REPORT_NAME_2013-07-01'
);
$bucket_contents = $this->objects->listObjects($bucket, $options);

回應就像......

{

 "kind": "storage#object",
 "id": "<bucket>/<report>.csv/1001",
 "selfLink": "https://www.googleapis.com/storage/v1beta2/b/<bucket>/o/<report>.csv",
 "name": "<report>.csv",
 "bucket": "<bucket>",
 "generation": "1001",
 "metageneration": "1",
 "contentType": "application/csv",
 "updated": "2013-07-22T10:21:08.811Z",
 "size": "806",
 "md5Hash": "wT01i....",
 "mediaLink": "https://www.googleapis.com/storage/v1beta2/b/<bucket>/o/<report>.csv?generation=1001&alt=media",
 "owner": {
  "entity": "user-00b........",
  "entityId": "00b490......."
 },
 "crc32c": "8y........",
 "etag": "CPjZ.........."
}

但是如何使用Google PHP客戶端下載文件...我不能使用file_get_contents,因為它不知道身份驗證詳細信息。 我發現的最好的東西是使用Google_Client,但響應只包含元數據而沒有對象/文件內容

$request = new Google_HttpRequest($object['selfLink']);
$response = $this->client->getIo()->authenticatedRequest($request);

老問題,但它讓我看向正確的方向。 selfLink是元數據請求的鏈接,您需要mediaLink來獲取實際的對象數據,它是getAuth而不是getIo

此腳本將輸出文件內容(假設您已初始化$client對象):

$service = new Google_Service_Storage($client);
$object = $service->objects->get('bucketname', 'objectname');
$request = new Google_Http_Request($object->getMediaLink());
$response = $client->getAuth()->authenticatedRequest($request);
echo $response->getResponseBody();

這是無效的apiclient〜2.0,看到UPGRADING.md文件在github上。

使用apiclient~2.0的工作代碼應該是:

$service = new Google_Service_Storage($client);
$object = $service->objects->get('bucketname', 'objectname');

// create an authorized HTTP client
$httpClient = $client->authorize();

$response = $httpClient->request('GET', $object->getMediaLink());

echo $response->getBody();

或授權現有的Guzzle客戶:

$service = new Google_Service_Storage($client);
$object = $service->objects->get('bucketname', 'objectname');

// add authorization to an existing client
$httpClient = new GuzzleHttp\Client();
$httpClient = $client->authorize($httpClient);

$response = $httpClient->request('GET', $object->getMediaLink());

echo $response->getBody();

對於下載文件,您需要授予所有用戶的READER訪問權限(您可以從谷歌網絡控制台或使用谷歌php api)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM