使用PHP将文件上传到Google云端硬盘文件夹

时间:2015-06-26 13:01:12

标签: php google-drive-api

我已成功将文件上传到Google云端硬盘。但是,我仍然不确定如何将其上传到文件夹中。我需要将其上传到文件夹结构中,如下所示:

Stats
    ACLLeauge
    ACLSydney
        Sorted
        Unsorted
            {Username}
                {FileHere}

{Username}字段是我将要传递的变量。 {FileHere}字段是图像需要去的地方。这是我目前的代码:

public function __construct()
{
    $this->instance = new \Google_Client();

    $this->instance->setApplicationName('DPStatsBot');
    $this->instance->setDeveloperKey(Config::getInstance()->getDriveDeveloperKey());
    $this->instance->setAuthConfigFile(Config::getInstance()->getClientSecret());
    $this->instance->addScope('https://www.googleapis.com/auth/drive');

    if(!file_exists(DP_STATS_BOT_DIR . '/' . Config::getInstance()->getAuthFile())) {
        Printer::write('Please navigate to this URL and authenticate with Google: ' . PHP_EOL .  $this->instance->createAuthUrl());
        Printer::raw('Authentication Code: ');

        $code = trim(fgets(STDIN));
        $token = $this->instance->authenticate($code);

        file_put_contents(DP_STATS_BOT_DIR . '/' . Config::getInstance()->getAuthFile(), $token);

        Printer::write('Saved auth token');

        $this->instance->setAccessToken($token);
    }
    else
    {
        $this->instance->setAccessToken(file_get_contents(DP_STATS_BOT_DIR . '/' . Config::getInstance()->getAuthFile()));
    }

    if($this->instance->isAccessTokenExpired())
    {
        $this->instance->refreshToken($this->instance->getRefreshToken());
        file_put_contents(DP_STATS_BOT_DIR . '/' . Config::getInstance()->getAuthFile(), $this->instance->getAccessToken());
    }

    $this->drive_instance = new \Google_Service_Drive($this->instance);
}

public function upload($image, $dpname)
{
    $file = new \Google_Service_Drive_DriveFile();
    $file->setTitle($dpname . '_' . RandomString::string() . '.jpg');

    $upload = $this->drive_instance->files->insert($file,
    [
        'data' => $image,
        'mimeType' => 'image/jpg',
        'uploadType' => 'media'
    ]);

    return $upload;
}

如果有人有任何建议,请告诉我!

由于

1 个答案:

答案 0 :(得分:1)

为此,您已按所需顺序插入文件夹。因此,在Drive根文件夹下添加Stats,然后按所需顺序添加所有文件夹。要添加文件夹,您需要提供mimeType as 'application/vnd.google-apps.folder'。检查此link以获取更多mimeType值。以下是有关如何在云端硬盘中插入文件夹的外部引用link

添加所有必需的文件夹后,您现在可以在{Username}文件夹下插入实际文件。您还可以参考此页面,了解如何在驱动器中insert文件。

希望有所帮助!

相关问题