2015-01-14 48 views
-1

我是Google雲端存儲的新用戶,請耐心等待。簡單更新Google雲端存儲中的文字內容

我正在嘗試創建一個文件編輯器,它從GCS獲取非二進制文件並將其保存回來。

我正在使用google-api-php-client。我一直在使用API​​進行很多實驗,瀏覽過,但我找不到合適的答案。

<?php 

class GCS_Driver { 
    /** @var Google_Service_Storage $driver */ 
    public $driver; 
    /** @var string $bucket */ 
    public $bucket; 

    public function updateObject($objectPath,$content) { 
     $updated = false; 
     try { 
      $postBody = new Google_Service_Storage_StorageObject(); 
      $updated = $this->driver->objects->patch($this->bucket,$objectPath,$postBody,array(
       'data' => $content // I know this is wrong, I am just showing the idea I am looking for to overwrite the content 
      )); 
     } catch (Exception $ex) { 
      // error log 
      return false; 
     } 

     if (!$updated) { 
      // error log 
      return false; 
     } 
     return true; 
    } 

} 

任何提示將不勝感激。

回答

0

我想出了工作。

基本上,只要保存臨時文件,並將其上傳到覆蓋現有

下面的代碼。

<?php 

class GCS_Driver { 
    /** @var Google_Client $client */ 
    public $client; 
    /** @var Google_Service_Storage $driver */ 
    public $driver; 
    /** @var string $bucket */ 
    public $bucket; 

    public function updateObject($objectPath,$content) { 
     $updated = false; 
     try { 
      $temp = tempnam(sys_get_temp_dir(), 'gcs'); 
      $handle = fopen($temp, "r+b"); 
      fwrite($handle, $content); 
      fseek($handle, 0); 
      $postBody = new Google_Service_Storage_StorageObject(); 
      $postBody->setName($objectPath); 
      $postBody->setUpdated(date("c")); 
      $postBody->setGeneration(time()); 
      $size = @filesize($temp); 
      $postBody->setSize($size); 
      $ext = @pathinfo($objectPath,PATHINFO_EXTENSION); 
      $ext = strtolower($ext); 
      $mimeType = $this->getContentType($ext); 
      $postBody->setContentType($mimeType); 
      $chunkSizeBytes = 1 * 1024 * 1024; 
      $this->client->setDefer(true); 
      $request = $this->driver->objects->insert($this->bucket,$postBody,array(
       'name' => $objectPath, 
       'predefinedAcl' => 'publicRead', 
       'projection' => 'full', 
      )); 
      $media = new Google_Http_MediaFileUpload(
        $this->client, 
        $request, 
        $mimeType, 
        null, 
        true, 
        $chunkSizeBytes 
      ); 
      $media->setFileSize($size); 
      $status = false; 
      while (!$status && !feof($handle)) { 
       $chunk = fread($handle, $chunkSizeBytes); 
       $status = $media->nextChunk($chunk); 
      } 
      fclose($handle); 
      unlink($temp); 
      if ($status) { 
       $updated = true; 
      } 
     } catch (Exception $ex) { 
      // error log 
      return false; 
     } 

     if (!$updated) { 
      // error log 
      return false; 
     } 

     // action log 
     return true; 
    } 
} 

歡迎任何新的反饋意見。

相關問題