2016-04-26 80 views
0

我完全是新的谷歌雲存儲(因爲我用亞馬遜S3到現在)。谷歌雲存儲文件通過PHP下載

我想設置我的網絡應用程序,以便用戶可以直接從Google雲端存儲下載文件。 我已經試過了,使用Google Api PHP Client,但沒有得到功能代碼。

我已經上傳了一個名爲「test.jpg放在」我的水桶測試文件「測試桶46856」,我想通過標識的URL下載(使用戶只有時間有限),但我不知道如何開始。

請幫忙。謝謝。

回答

-1

//編輯:

找到完美的解決方案。此處所有其他人也在尋找此解決方案的鏈接: https://gist.github.com/stetic/c97c94a10f9c6b591883

<?php 
/* 
* PHP Example for Google Storage Up- and Download 
* with Google APIs Client Library for PHP: 
* https://github.com/google/google-api-php-client 
*/ 

include("Google/Client.php"); 
include("Google/Service/Storage.php"); 

$serviceAccount  = "[email protected]"; 
$key_file  = "/path/to/keyfile.p12"; 
$bucket   = "my_bucket"; 
$file_name  = "test.txt"; 
$file_content  = "01101010 01110101 01110011 01110100 00100000 01100001 00100000 01110100 01100101 01110011 01110100"; 

$auth = new Google_Auth_AssertionCredentials(
        $serviceAccount, 
        array('https://www.googleapis.com/auth/devstorage.read_write'), 
        file_get_contents($key_file) 
        ); 

$client = new Google_Client(); 
$client->setAssertionCredentials($auth); 
$storageService = new Google_Service_Storage($client); 

/*** 
* Write file to Google Storage 
*/ 

try 
{ 
    $postbody = array( 
      'name' => $file_name, 
      'data' => $file_content, 
      'uploadType' => "media" 
      ); 
    $gsso = new Google_Service_Storage_StorageObject(); 
    $gsso->setName($file_name); 
    $result = $storageService->objects->insert($bucket, $gsso, $postbody); 
    print_r($result); 

}  
catch (Exception $e) 
{ 
    print $e->getMessage(); 
} 

/*** 
* Read file from Google Storage 
*/ 

try 
{ 
    $object = $storageService->objects->get($bucket, $file_name); 
    $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(); 
}  
catch (Exception $e) 
{ 
    print $e->getMessage(); 
}