2

Google PHP API CLIENT를 사용하여 작은 크기의 파일을 Google Cloud Storage에 성공적으로 업로드 할 수는 있지만 300MB 파일은 업로드 할 수 없습니다. 메모리 오류로 돌아갑니다. 내 코드는 다음과 같습니다.PHP API를 사용하여 Google Cloud Storage에 다시 업로드 할 수 있습니다.

$storage = new Google_Service_Storage($client); 

    $file_name = "filenameo.zip"; 

    $obj = new Google_Service_Storage_StorageObject(); 
    $obj->setName($file_name); 

    $resp = $storage->objects->insert(
     "bucketname", 
     $obj, 
     array('name' => $file_name, 'data' => file_get_contents("300mb-file.zip"), 'uploadType' => 'media') 
    ); 

UploadType을 재개 가능으로 변경하려고 시도했지만 운이 없습니다. 도와주세요.

업데이트 : Brandon Yarbrough 대답

수신 오류로 HTTP를 사용 (치명적인 오류 : catch되지 않은 예외 'Google_IO_Exception'는)

$storage = new Google_Service_Storage($client); 

$obj = new Google_Service_Storage_StorageObject(); 

$obj->setName("filenameo.zip"); 
$obj->setBucket("bucketname"); 


$filen = "300mb-file.zip"; 
$mimetype = mime_content_type($filen); 


$chunkSizeBytes = 1 * 1024 * 1024; 
$client->setDefer(true); 
$status = false; 



$filetoupload = array('name' => $file_name, 'data' => $filen, 'uploadType' => 'media'); 

$request = $storage->objects->insert("bucketname",$obj,$filetoupload); 

$media = new Google_Http_MediaFileUpload($client, $request, $mimetype, $chunkSizeBytes); 
$handle = fopen($filen, "rb"); 
while (!$status && !feof($handle)) { 
    $chunk = fread($handle, $chunkSizeBytes); 
    $status = $media->nextChunk($chunk); 
} 

$result = false; 
if($status != false) { 
    $result = $status; 
} 

fclose($handle); 
// Reset to the client to execute requests immediately in the future. 
$client->setDefer(false); 
+0

오류로 '치명적인 오류 : 캐치되지 않은 예외'Google_IO_Exception '이외의 것이 있습니까? – Aidan

답변

5

는 아래의 코드 작업을 얻었다.

<?php 

    require_once("google-api/autoload.php"); 
    //require_once("google-api/src/Google/Client.php"); 
    //require_once("google-api/src/Google/Service/Storage.php"); 
    //require_once("google-api/src/Google/Http/MediaFileUpload.php"); 
    session_start(); 
    /** 
     * Connect to Google Cloud Storage API 
    */ 
    $client = new Google_Client(); 
    $client->setApplicationName("ApplicationName"); 

    // $stored_access_token - your cached oauth access token 
    if($stored_access_token) { 
     $client->setAccessToken($stored_access_token); 
    } 

    $credential = new Google_Auth_AssertionCredentials(
    "[email protected]", 
    array('https://www.googleapis.com/auth/devstorage.read_write'), 
    file_get_contents("pathtokey/mykeyhere-7845b2eb92c9.p12") 
    ); 

    $client->setAssertionCredentials($credential); 
    if($client->getAuth()->isAccessTokenExpired()) { 
     $client->getAuth()->refreshTokenWithAssertion($credential); 
     // Cache the access token however you choose, getting the access token with $client->getAccessToken() 
    } 

    $storage = new Google_Service_Storage($client); 



    if (isset($_GET['code'])) { 
     if (strval($_SESSION['state']) !== strval($_GET['state'])) { 
      die('The session state did not match.'); 
     } 


     $client->authenticate($_GET['code']); 
     $_SESSION['token'] = $client->getAccessToken(); 
     header('Location: ' . $redirect); 
    } 
    if (isset($_SESSION['token'])) { 
     $client->setAccessToken($_SESSION['token']); 
    } 





    if ($client->getAccessToken()) { 


      $sfilename = "mfile.zip"; //filename here 
      $obj = new Google_Service_Storage_StorageObject(); 

      $obj->setName($sfilename); 
      $obj->setBucket("myBucketS"); //bucket name here 


      $filen = "pathtofile/uploadthis.zip"; 

      $mimetype = mime_content_type($filen); 


      $chunkSizeBytes = 1 * 1024 * 1024; 
      $client->setDefer(true); 
      $status = false; 

      $filetoupload = array('name' => $sfilename, 'uploadType' => 'resumable'); 

      $request = $storage->objects->insert("myBucketS",$obj,$filetoupload); 

      $media = new Google_Http_MediaFileUpload($client, $request, $mimetype, null, true, $chunkSizeBytes); 
      $media->setFileSize(filesize($filen)); 
      $handle = fopen($filen, "rb"); 

      while (!$status && !feof($handle)) { 
       $chunk = fread($handle, $chunkSizeBytes); 
       $status = $media->nextChunk($chunk); 
      } 

      $result = false; 
      if($status != false) { 
       $result = $status; 
      } 

      fclose($handle); 
      // Reset to the client to execute requests immediately in the future. 
      $client->setDefer(false); 

     } else { 
     // If the user hasn't authorized the app, initiate the OAuth flow 
     $state = mt_rand(); 
     $client->setState($state); 
     $_SESSION['state'] = $state; 
     $authUrl = $client->createAuthUrl(); 
    } 
    $_SESSION['token'] = $client->getAccessToken(); 

    print_r($status); 


?> 
4

file_get_contents 문자 그대로 메모리에 파일의 내용을로드 문자열. 귀하의 애플 리케이션은 아마도 300MB의 메모리가 추가로 필요하지 않을 것입니다.

대신 청크로 파일을 읽고 업로드하는 것이 좋습니다. Google_Http_MediaFileUpload이이를위한 유용한 도구입니다. 좋은 예는 여기있다 : https://developers.google.com/api-client-library/php/guide/media_upload

중요한 부분은이 비트입니다 :

$media = new Google_Http_MediaFileUpload($client, $request, ......, $chunkSizeBytes) 
$handle = fopen("path/to/file", "rb"); 
while (!$status && !feof($handle)) { 
    $chunk = fread($handle, $chunkSizeBytes); 
    $status = $media->nextChunk($chunk); 
} 
관련 문제