首页 文章

通过PHP下载Google Cloud 存储文件

提问于
浏览
0

我对Google Cloud 端存储完全陌生(因为我直到现在才使用Amazon S3) .

我想设置我的网络应用程序,以便用户可以直接从Google Cloud 端存储下载文件 . 我已经尝试过,使用Google Api PHP Client,但没有得到功能代码 .

我上传了一个名为“test.jpg " to my bucket " test-bucket-46856”的测试文件,我想通过签名网址下载(这样用户只能有时间限制访问),但我不知道如何启动它 .

请帮忙 . 谢谢 .

1 回答

  • -1

    //Edit:

    找到了完美的解决方案这里是所有其他人也在寻找这个解决方案的链接: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     = "1234-xyz@developer.gserviceaccount.com";
    $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();
    }
    

相关问题