通过PHP从Google云端存储下载文件

时间:2016-06-22 21:16:53

标签: php google-cloud-storage google-cloud-platform

我尝试使用PHP从Google云存储中的文件夹中下载文件。我可以上传好。我已经尝试了一些我在这里找到的代码,但是Laravel告诉我找不到课程Google_Http_Request

这是我尝试的代码:

$request = new Google_Http_Request($object['mediaLink'], 'GET');
$signed_request = $client->getAuth()->sign($request);
$http_request = $client->getIo()->makeRequest($signed_request);
echo $http_request->getResponseBody();

1 个答案:

答案 0 :(得分:2)

以下是如何使用最新版本的client library (v2.0)下载对象的示例:

// Authenticate your API Client
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Storage::DEVSTORAGE_FULL_CONTROL);

$storage = new Google_Service_Storage($client);

try {
    // Google Cloud Storage API request to retrieve the list of objects in your project.
    $object = $storage->objects->get($bucketName, $objectName);
} catch (Google_Service_Exception $e) {
    // The bucket doesn't exist!
    if ($e->getCode() == 404) {
        exit(sprintf("Invalid bucket or object names (\"%s\", \"%s\")\n", $bucketName, $objectName));
    }
    throw $e;
}

// build the download URL
$uri = sprintf('https://storage.googleapis.com/%s/%s?alt=media&generation=%s', $bucketName, $objectName, $object->generation);
$http = $client->authorize();
$response = $http->get($uri);

if ($response->getStatusCode() != 200) {
    exit('download failed!' . $response->getBody());
}

// write the file (or do whatever you'd like with it)
file_put_contents($downloadName, $response->getBody());

您可以在此Samples Repository

中找到有关使用存储API的其他示例

还开发了一个名为gcloud-php的新版库,其中有一些documentation用于调用Google云端存储。