我在尝试使用https://code.google.com/p/google-api-php-client/上的php客户端从谷歌云存储下载文件时遇到问题
我已经对自己进行了身份验证,使用下面的代码,我可以返回一个包含指向我的文件的链接的对象
$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);发布于 2015-02-20 23:35:52
老问题,但它让我找到了正确的方向。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();发布于 2016-11-30 20:50:52
这对于apiclient ~2.0无效,请参阅github中的UPGRADING.md文件。
使用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();发布于 2013-08-16 15:30:30
要下载文件,您需要授予读者访问allUsers的权限(您可以从google web控制台或使用google php api进行)。
https://stackoverflow.com/questions/17855705
复制相似问题