如何在我的脚本/自动加载中包含Google App Engine for PHP?

时间:2015-05-20 09:37:41

标签: php google-app-engine google-api google-cloud-storage google-api-php-client

我在Ubuntu网络服务器上有一个网站(不是应用程序而不是App Engine托管),我想使用谷歌云存储来上传/下载大文件。我正在尝试将文件直接上传到无法正常工作的Google Cloud Storage(可能是因为我犯了一些基本错误)。

我已安装Google Cloud SDK并已下载并解压缩Google App Engine。如果我现在包含CloudStorageTools.php,我会收到错误:

  

类'google \ appengine \ CreateUploadURLRequest'找不到“

我的脚本如下所示:

require_once 'google/appengine/api/cloud_storage/CloudStorageTools.php';
use google\appengine\api\cloud_storage\CloudStorageTools;
$options = [ 'gs_bucket_name' => 'test' ];
$upload_url = CloudStorageTools::createUploadUrl( '/test.php' , $options );

2 个答案:

答案 0 :(得分:1)

Google API PHP Client可让您连接到任何Google API,包括Cloud Storage APIHere是一个示例,here是一个入门指南。

答案 1 :(得分:1)

如果你想使用谷歌应用引擎(gae)的功能,你需要托管gae,这可能会对你的应用架构产生更大的影响(它使用自定义谷歌编译的php版本,有限的库和没有本地文件处理,所以所有功能都需要进入blob store或gcs - Google Cloud Storage。

在ubuntu上运行PHP应用程序,最好的办法是使用google-api-php-client连接到存储JSON api。 不幸的是,文档不是很好的PHP。您可以在How to rename or move a file in Google Cloud Storage (PHP API)中查看我的答案,了解如何获取/复制/删除对象。 要上传,我建议您检索预签名的上传网址,如下所示:

//get google client and auth token for request
$gc = \Google::getClient();
if($gc->isAccessTokenExpired())
    $gc->getAuth()->refreshTokenWithAssertion();
$googleAccessToken = json_decode($gc->getAccessToken(), true)['access_token'];

//compose url and headers for upload url request
$initUploadURL = "https://www.googleapis.com/upload/storage/v1/b/"
    .$bucket."/o?uploadType=resumable&name="
    .urlencode($file_dest);

//Compose headers
$initUploadHeaders = [
    "Authorization"             =>"Bearer ".$googleAccessToken,
    "X-Upload-Content-Type"     => $mimetype,
    "X-Upload-Content-Length"   => $filesize,
    "Content-Length"            => 0,
    "Origin"                    => env('APP_ADDRESS')
];

//send request to retrieve upload url
$req = $gc->getIo()->makeRequest(new \Google_Http_Request($initUploadURL, 'POST', $initUploadHeaders));

// pre signed upload url that allows client side upload
$presigned_upload_URL = $req->getResponseHeader('location');

将该URL发送到您的客户端,您可以使用它将文件直接输出到您的存储桶上,并使用上传脚本生成适当的PUT请求。这是AngularJS中使用ng-file-upload的示例:

file.upload = Upload.http({
    url: uploadurl.url,
    skipAuthorization: true,
    method: 'PUT',
    filename: file.name,
    headers: {
        "Content-Type": file.type !== '' ? file.type : 'application/octet-stream'
    },
    data: file
});

祝你好运 - 如果你不想通过app引擎一路google,那么gcs是一个艰难的选择!