Google云端硬盘API-将文件插入共享/团队云端硬盘

时间:2020-06-29 20:34:37

标签: php google-drive-api google-drive-team-drive

所以我有这段代码可以将文件上传到Google云端硬盘。我已成功将其上传到任何“我的云端硬盘” 文件夹中,但现在我希望将其上传到任何 Team Drive 文件夹中。我怎样才能做到这一点?我正在为此使用Google Drive API V2。

我见过某个地方可以使用supportAllDrives,但我不知道将其放置在何处。

index.php

<?php
session_start();
include 'config.php';
$url_array = explode('?', 'http://'.$_SERVER ['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$url = $url_array[0];

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';

$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($url);
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
if (isset($_GET['code'])) {
    $_SESSION['accessToken'] = $client->authenticate($_GET['code']);
    header('location:'.$url);exit;
} elseif (!isset($_SESSION['accessToken'])) {
    $client->authenticate();
}

$files= array();
$dir = dir('files');
while ($file = $dir->read()) {
    if ($file != '.' && $file != '..') {
        $files[] = $file;
    }
}
$dir->close();

if (!empty($_POST)) {
    $client->setAccessToken($_SESSION['accessToken']);
    $service = new Google_DriveService($client);
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $file = new Google_DriveFile(['supportsAllDrives'=>true]);
    foreach ($files as $file_name) {
        $file_path = 'files/'.$file_name;
        $mime_type = finfo_file($finfo, $file_path);
        $file->setTitle($file_name);
        $file->setDescription('This is a '.$mime_type.' document');
        $file->setMimeType($mime_type);
        
        $parent = new Google_ParentReference(); //previously Google_ParentReference
        $parent->setId('1wj_QbpXn7x0OOJ1Zf4k57BSR5n1uR_xC');//$folderid = determined folder id
        $file->setParents(array($parent));
    
        
        $service->files->insert(
            $file,
            array(
                'data' => file_get_contents($file_path),
                'mimeType' => $mime_type
            )
        );
    }
    finfo_close($finfo);
    header('location:'.$url);exit;
    

}

include 'index.phtml';

0 个答案:

没有答案