使用带有PHP的google驱动器api将文件上传到特定文件夹

Ali*_*Ali 9 php google-drive-api google-api-php-client

我正在使用谷歌驱动器api上传文件,这是我的代码到目前为止,文件上传到我的根目录,我想更改到另一个文件夹的路径,

   <?php
        error_reporting(E_ALL);
        ini_set('display_errors', 1);
        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();
        // Get your credentials from the APIs Console
        $client->setClientId('***');
        $client->setClientSecret('***');
        $client->setRedirectUri('http://***');
        $client->setScopes(array('https://www.googleapis.com/auth/drive'));

        if(empty($_GET['code']))
        {
            $client->authenticate();
        }

        $myfile= "video.mp4";
        $type='video/mp4';

        $service = new Google_DriveService($client);

        // Exchange authorization code for access token
        $accessToken = $client->authenticate($_GET['code']);
        $client->setAccessToken($accessToken);


        //Insert a file

        $file = new Google_DriveFile();
        $file->setTitle('filename.mp4');
        $file->setDescription('A video');
        $file->setMimeType($type);

        $data = file_get_contents($myfile);

        $createdFile = $service->files->insert($file, array(
              'data' => $data,
              'mimeType' => $type,
            ));

        print_r($createdFile);
        echo "<br />";
Run Code Online (Sandbox Code Playgroud)

我尝试了stackoverflow的几个帖子,但没有一个对我有用我有错误,提前谢谢

fan*_*iva 6

看来该班级Google_Service_Drive_ParentReference()不再有效。但是,以下代码对我有用:

$fileMetadata = new Google_Service_Drive_DriveFile(array(
        //Set the Random Filename
        'name' => $rdmName,
        //Set the Parent Folder
        'parents' => array('0BzaRxkCDivjIM1pUYU1SLWVxOGM') // this is the folder id
    ));

    try{

        $newFile = $drive_service->files->create(
            $fileMetadata,
            array(
                'data' => file_get_contents(TESTFILE),
                'mimeType' => 'application/pdf',
                'uploadType' => 'media'
            )
        );


    } catch(Exception $e){

        echo 'An error ocurred : ' . $e->getMessage();

    }
Run Code Online (Sandbox Code Playgroud)


Bur*_*gan 2

设置父 ID 列表应该可以。我们的公共文档包含每个 API 方法的工作片段。请先看一下它们:https ://developers.google.com/drive/v2/reference/files/insert

$file->setParents([{'id': parent_id}])
Run Code Online (Sandbox Code Playgroud)