0

以下是代碼。其中上傳/創建/插入谷歌驅動器上的文件使用谷歌驅動器PHP API成功,但上傳文件後,它的內容是空的。文件上傳與空的內容使用谷歌驅動器php api

session_start(); 
set_include_path("/src/" . PATH_SEPARATOR . get_include_path()); 
require_once 'Google/Client.php'; 
require_once 'Google/Service/Drive.php'; 

$client_id = 'XXXXXX'; 
$client_secret = 'XXXXXX'; 
$redirect_uri = 'XXXXXX'; 

$client = new Google_Client(); 
$client->setClientId($client_id); 
$client->setClientSecret($client_secret); 
$client->setRedirectUri($redirect_uri); 
$client->addScope("https://www.googleapis.com/auth/drive"); 

$service = new Google_Service_Drive($client); 

if (isset($_REQUEST['logout'])) { 
    unset($_SESSION['upload_token']); 
} 

if (isset($_GET['code'])) { 
    $client->authenticate($_GET['code']); 
    $_SESSION['upload_token'] = $client->getAccessToken(); 
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; 
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); 
} 

if (isset($_SESSION['upload_token']) && $_SESSION['upload_token']) { 
    $client->setAccessToken($_SESSION['upload_token']); 
    if ($client->isAccessTokenExpired()) { 
    unset($_SESSION['upload_token']); 
    } 
} else { 
    $authUrl = $client->createAuthUrl(); 
} 

$filename = "file.csv"; 

echo "<BR><BR>stage 1"; 

if ($client->getAccessToken()) 
{  
    $data = file_get_contents($filename); 

    if (isset($data) && $data) 
    { 
     $file = new Google_Service_Drive_DriveFile(); 
     echo "<BR><BR>stage 2"; 
     if (isset($file)) 
     {    
      $file -> setTitle("gsexpo"); 
      $file -> setMimeType("application/vnd.google-apps.spreadsheet"); 

      if (isset($file -> parentId) && $file -> parentId != null) { 
       $parent = new Google_ParentReference(); 
       $parent -> setId($file -> parentId); 
       $file -> setParents(array($parent)); 
      } 

      echo "<BR><BR>stage 3"; 

      $result2 = $service->files->insert(
       $file, 
       array(
        'data' => $data, 
        'mimeType' => "application/vnd.google-apps.spreadsheet",     
        'convert' => true 
       )); 

      echo "Result: ";    
      var_dump($result2->title); 
     } 
     else 
     { 
      echo "No file object"; 
     } 
    } 
    else 
    { 
     echo "File read failed";  
    } 
} 
if (isset($authUrl)) 
{  echo "<a href='".$authUrl."'>Connect Me!</a>"; } 

這裏是我的谷歌api的PHP客戶端庫,我正在使用這個目的的鏈接。

https://github.com/google/google-api-php-client

回答

0

您需要將「uploadType」參數添加到您的插入請求陣列。例如:

$result2 = $service->files->insert(
    $file, 
    array(
     'data' => $data, 
     'mimeType' => "application/vnd.google-apps.spreadsheet",     
     'convert' => true, 
     'uploadType' => 'media', 
    ) 
); 
+0

我已經試過這個,但沒有發生。 – Sagar

0

只需使用如下代碼:

$result2 = $service->files->create($file, array(
      'data' => $data, 
      'mimeType' => 'application/vnd.google-apps.spreadsheet', 
      'uploadType' => 'multipart' 
     )); 

讓我知道如果任何問題。

相關問題