Google Drive PHP API - Simple File Upload

后端 未结 3 1846
情歌与酒
情歌与酒 2020-11-27 04:01

I am trying to write a small script to upload a local file to Google Drive, using Google Drive PHP API. The documentation is very poor maintained, but so far I am pretty sur

3条回答
  •  广开言路
    2020-11-27 04:29

    Use this code to authenticate and upload a test file. You need to set (and also in console) to this document itself to authenticate.

    require_once 'Google/Client.php';
    require_once 'Google/Service/Drive.php';
    
    $client = new Google_Client();
    // Get your credentials from the console
    $client->setClientId('');
    $client->setClientSecret('');
    $client->setRedirectUri('');
    $client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
    
    session_start();
    
    if (isset($_GET['code']) || (isset($_SESSION['access_token']) && $_SESSION['access_token'])) {
        if (isset($_GET['code'])) {
            $client->authenticate($_GET['code']);
            $_SESSION['access_token'] = $client->getAccessToken();
        } else
            $client->setAccessToken($_SESSION['access_token']);
    
        $service = new Google_Service_Drive($client);
    
        //Insert a file
        $file = new Google_Service_Drive_DriveFile();
        $file->setName(uniqid().'.jpg');
        $file->setDescription('A test document');
        $file->setMimeType('image/jpeg');
    
        $data = file_get_contents('a.jpg');
    
        $createdFile = $service->files->create($file, array(
              'data' => $data,
              'mimeType' => 'image/jpeg',
              'uploadType' => 'multipart'
            ));
    
        print_r($createdFile);
    
    } else {
        $authUrl = $client->createAuthUrl();
        header('Location: ' . $authUrl);
        exit();
    }
    

提交回复
热议问题