在Google云端硬盘中创建文件夹并插入文件

时间:2014-08-21 10:17:42

标签: php google-drive-api

我正在尝试在云端硬盘中创建一个新文件夹,并将一个(或多个)文件上传到该创建的文件夹。我使用下面的代码,但结果是文件夹和文件都放在我的驱动器的根目录中。

$client->setAccessToken($_SESSION['accessToken']);

//create folder
$folder_mime = "application/vnd.google-apps.folder";
$folder_name = 'New Folder';

$service = new Google_DriveService($client);
$folder = new Google_DriveFile();

$folder->setTitle($folder_name);
$folder->setMimeType($folder_mime);
$service->files->insert($folder);

//upload file
$file_name = $_FILES["uploadFile"]["name"];
$file_mime = $_FILES["uploadFile"]["type"];
$file_path = $_FILES["uploadFile"]["tmp_name"];

$service = new Google_DriveService($client);
$file = new Google_DriveFile();

$file->setParents(array($folder_name));
$file->setTitle($file_name);
$file->setDescription('This is a '.$file_mime.' document');
$file->setMimeType($file_mime);
$service->files->insert(
    $file,
    array(
        'data' => file_get_contents($file_path)
    )
);

1 个答案:

答案 0 :(得分:3)

感谢@pinoyyid,这是适合我的代码。

$client->setAccessToken($_SESSION['accessToken']);

//create folder
$folder_mime = "application/vnd.google-apps.folder";
$folder_name = 'New Folder';

$service = new Google_DriveService($client);
$folder = new Google_DriveFile();

$folder->setTitle($folder_name);
$folder->setMimeType($folder_mime);
$newFolder = $service->files->insert($folder);

$parentId  = $newFolder['id'];
//upload file
$file_name = $_FILES["uploadFile"]["name"];
$file_mime = $_FILES["uploadFile"]["type"];
$file_path = $_FILES["uploadFile"]["tmp_name"];

$service = new Google_DriveService($client);
$file = new Google_DriveFile();

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

$file->setTitle($file_name);
$file->setDescription('This is a '.$file_mime.' document');
$file->setMimeType($file_mime);
try {
return $service->files->insert(
    $file,
    array(
        'data' => file_get_contents($file_path)        
    )
);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}