在根目录下创建文件夹并将文件上传到该文件夹​​google drive api

问题描述:

我想使用CURL在googledrive根目录中创建文件夹.文件已上传到驱动器,但是我需要创建一个文件夹并将文件上传到该文件夹​​.

I want to create folder in googledrive root directory using CURL. File is uploaded to drive but I need to create a folder and upload file to that folder.

根据@hanshenrik代码创建文件夹的要求,Move文件不起作用

我的更新代码:

$REDIRECT_URI = 'http' . ($_SERVER['SERVER_PORT'] == 80 ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];
$SCOPES = array($GAPIS_AUTH . 'drive', $GAPIS_AUTH . 'drive.file', $GAPIS_AUTH . 'userinfo.email', $GAPIS_AUTH . 'userinfo.profile');
$STORE_PATH = 'credentials.json';

function uploadFile($credentials, $filename, $targetPath,$folderId)
{

    global $GAPIS;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');

   //$content =  { title  "mypdf.pdf", description = "mypdf.pdf", mimeType = "application/pdf" };

   $contentArry = array('name' =>'veridoc', 'parents' => array('17dVe2GYpaHYFdFn1by5-TYKU1LXSAwkp'));
   $contentArry = json_encode($contentArry);



    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
    //curl_setopt($ch, CURLOPT_POSTFIELDS,$contentArry);
    curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER,
            array('Content-Type : application/pdf','Content-Length:' . filesize($filename),'Authorization: Bearer ' . getAccessToken($credentials))
    );

    $postResult = curl_exec($ch);
    curl_close($ch);

    return json_decode($postResult, true);
}
function RenameUploadedFile($id,$credentials,$filename)
{

 $ch = curl_init();
    curl_setopt_array ( $ch, array (
            CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files/' . urlencode ( $id ),
            CURLOPT_POST => 1,
            CURLOPT_RETURNTRANSFER => true,     
            CURLOPT_POSTFIELDS => json_encode ( array (
                    'name' => $filename  
            ) ),
            CURLOPT_CUSTOMREQUEST => 'PATCH',
            CURLOPT_HTTPHEADER => array (
                    'Content-Type : application/json',
                    'Authorization: Bearer ' . getAccessToken ( $credentials ) 
            ) 

    ) );
    curl_exec($ch);
    curl_close($ch);
    return true;
}

  function CreateGDFolder($credentials,$foldername)
    {


            $curl = curl_init();
            curl_setopt_array ( $curl, array (
            CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files',
            CURLOPT_POST => 1,
            CURLOPT_RETURNTRANSFER => true,             
            CURLOPT_POSTFIELDS => json_encode ( array (
                // Earlier it was title changed to name
                "name" => $foldername,
                "mimeType" => "application/vnd.google-apps.folder"

            ) ),
            // Earlier it was PATCH changed to post
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_HTTPHEADER => array (
                'Content-Type : application/json',
                'Authorization: Bearer ' . getAccessToken ( $credentials ) 
            ) 

            ) );

           $response = curl_exec($curl);

        return json_decode($response, true);
}



function getStoredCredentials($path)
{

    $credentials = json_decode(file_get_contents($path), true);

    if (isset($credentials['refresh_token']))
    {   
        return $credentials;
    }


    $expire_date = new DateTime();
    $expire_date->setTimestamp($credentials['created']);
    $expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));

    $current_time = new DateTime();

    if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
    {
        $credentials = null;
        unlink($path);
    }

    return $credentials;
}

function storeCredentials($path, $credentials)
{

    $credentials['created'] = (new DateTime())->getTimestamp();
    file_put_contents($path, json_encode($credentials));
    return $credentials;
}

function requestAuthCode()
{

    global $GOAUTH, $CLIENT_ID, $REDIRECT_URI, $SCOPES;
    $url = sprintf($GOAUTH . 'auth?scope=%s&redirect_uri=%s&response_type=code&client_id=%s&approval_prompt=force&access_type=offline',
            urlencode(implode(' ', $SCOPES)), urlencode($REDIRECT_URI), urlencode($CLIENT_ID)
    );
    header('Location:' . $url);
}

function requestAccessToken($access_code)
{

    global $GOAUTH, $CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI;
    $url = $GOAUTH . 'token';
    $post_fields = 'code=' . $access_code . '&client_id=' . urlencode($CLIENT_ID) . '&client_secret=' . urlencode($CLIENT_SECRET)
            . '&redirect_uri=' . urlencode($REDIRECT_URI) . '&grant_type=authorization_code';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    curl_setopt($ch, CURLOPT_POST, true);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);

    $result = curl_exec($ch);

    curl_close($ch);

    return json_decode($result, true);
}

function getAccessToken($credentials)
{

    $expire_date = new DateTime();
    $expire_date->setTimestamp($credentials['created']);
    $expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));

    $current_time = new DateTime();

    if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
        return $credentials['refresh_token'];
    else
        return $credentials['access_token'];

}

function authenticate()
{

    global $STORE_PATH;

    if (file_exists($STORE_PATH))
        $credentials = getStoredCredentials($STORE_PATH);
    else
        $credentials = null;

    if (!(isset($_GET['code']) || isset($credentials)))
        requestAuthCode();

    if (!isset($credentials))
        $credentials = requestAccessToken($_GET['code']);

    if (isset($credentials) && isset($credentials['access_token']) && !file_exists($STORE_PATH))
        $credentials = storeCredentials($STORE_PATH, $credentials);

    return $credentials;
}   

$credentials = authenticate();

$folderresponse=CreateGDFolder($credentials,"veridoc");
$folderID= $folderresponse['id'];
$folder_id=$folderID;
$filename="veridoc".date('_Y_m_d_H_i_s').".pdf";

$result = uploadFile($credentials, 'veridoc.pdf', '',$folderID);

// File rename to original

$id=$result['id'];
$file_id=$id;


if(isset($folderID)){

//Upload a file 
if(RenameUploadedFile($id,$credentials,$filename))
{
echo "We have uploaded ".$filename." to drive";
}
else{
echo "can't rename file";
}
}



try {
    $ch = curl_init ();
    curl_setopt_array ( $ch, array (
            CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files/' . urlencode ( $file_id ),
            CURLOPT_POST => 1,
            CURLOPT_RETURNTRANSFER => true,     
            CURLOPT_POSTFIELDS => json_encode (array(
            'addParents' => $folder_id,
            'removeParents' => 'root',
            'fields' => 'id, parents') ),
            CURLOPT_CUSTOMREQUEST => 'PATCH',
            CURLOPT_HTTPHEADER => array (
                    'Content-Type : application/pdf',
                    'Authorization: Bearer ' . getAccessToken ( $credentials ) 
            ) 

    ) );
    $resp = curl_exec ( $ch );
    $parsed = json_decode ( $resp, true );

} finally{
    curl_close ( $ch );
}

这是我的工作示例:

要连接Google驱动程序:

public function connect(Request $request)
    {
        $user = Auth::user();

        $client = new \Google_Client();
        $client->setHttpClient(new \GuzzleHttp\Client(['verify' => false]));
        $client->setClientId('xxxx');
        $client->setClientSecret('xxxxxx');
        $client->setRedirectUri(url('copywriter/connect'));
        $client->setAccessType('offline');
        $client->setApprovalPrompt('force');
        $client->setScopes(array('https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/drive.appfolder'));
        if (isset($request->code)) {
            $authCode = trim($request->code);
            $accessToken = $client->authenticate($authCode);
            $copywriter->gd_access_token=json_encode($accessToken, JSON_PRETTY_PRINT);
            $copywriter->save();
        } else {
            $authUrl = $client->createAuthUrl();
            return redirect($authUrl);
        }

        $found=$this->search_gd("files");
        if (!isset($found['file_id'])) {
            $found=$this->create_folder_gd("copify_files");
            $copywriter->gd_folder_id=$found["file_id"];
            $copywriter->save();
        }
        return redirect(route("copywriter.index"));
    }

发送到Google云端硬盘

    public function send_to_gd($name)
        {
            $user = Auth::user();
            $copywriter=Copywriter::where('user_id', $user->id)->first();
            $folderId = $copywriter->gd_folder_id;
            $client=$this->getClient();
            $service = new \Google_Service_Drive($client);
            $fileMetadata = new \Google_Service_Drive_DriveFile(array(
            'name' => $name,'mimeType' => 'application/vnd.google-apps.document','parents' => array($folderId)));
            $file = $service->files->create($fileMetadata, array(
            'mimeType' => 'application/vnd.google-apps.document',
            'uploadType' => 'multipart',
            'fields' => 'id'));
            return $file->id;
        }

请求的客户

public function getClient($user=null)
    {
        if ($user==null) {
            $user = Auth::user();
        }
        $copywriter=Copywriter::where('user_id', $user->id)->first();
        $client = new \Google_Client();
        $client->setHttpClient(new \GuzzleHttp\Client(['verify' => false]));
        $client->setClientId('xxxx');
        $client->setClientSecret('xxxxx');
        $client->setRedirectUri(url('copywriter/connect'));
        $client->setAccessType('offline');
        $client->setApprovalPrompt('force');
        $client->setScopes(array('https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/drive.appfolder'));


        $data=json_decode($copywriter->gd_access_token, true);

        $client->setAccessToken($data);

        // Refresh the token if it's expired.
        if ($client->isAccessTokenExpired()) {
            $oldAccessToken=$client->getAccessToken();
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            $accessToken=$client->getAccessToken();
            $accessToken['refresh_token']=$oldAccessToken['refresh_token'];

            $copywriter->gd_access_token=json_encode($accessToken, JSON_PRETTY_PRINT);
            $copywriter->save();
        }
        return $client;
    }

在Google云端硬盘中搜索

public function search_gd($name)
    {
        $client=$this->getClient();
        $service = new \Google_Service_Drive($client);
        $pageToken = null;
        do {
            $response = $service->files->listFiles(array(
        'q' => "mimeType='application/vnd.google-apps.folder' and name='".$name."'",
        'spaces' => 'drive',
        'pageToken' => $pageToken,
        'fields' => 'nextPageToken, files(id, name)',
    ));
            foreach ($response->files as $file) {
                return ['file_name'=>$file->name,'file_id'=>$file->id];
                printf("Found file: %s (%s)\n", $file->name, $file->id);
            }
            if (isset($repsonse)) {
                $pageToken = $repsonse->pageToken;
            }
        } while ($pageToken != null);
    }

在Google云端硬盘上创建文件夹

public function create_folder_gd($name)
    {
        $client=$this->getClient();
        $service = new \Google_Service_Drive($client);
        $fileMetadata = new \Google_Service_Drive_DriveFile(array(
    'name' => $name,
    'mimeType' => 'application/vnd.google-apps.folder'));
        $file = $service->files->create($fileMetadata, array(
    'fields' => 'id'));
        return ['file_name'=>$name,'file_id'=>$file->id];
    }

在Google云端硬盘上创建文档

public function create_document($name, $content_id=null)
    {
        $user = Auth::user();
        $copywriter=Copywriter::where('user_id', $user->id)->first();
        $folderId = $copywriter->gd_folder_id;
        $client=$this->getClient();
        $service = new \Google_Service_Drive($client);
        $fileMetadata = new \Google_Service_Drive_DriveFile(array(
      'name' => $name,'mimeType' => 'application/vnd.google-apps.document','parents' => array($folderId)));
        $file = $service->files->create($fileMetadata, array(
      'mimeType' => 'application/vnd.google-apps.document',
      'uploadType' => 'multipart',
      'fields' => 'id'));
        if ($content_id!=null) {
            $content=Content::findOrFail($content_id);
            $content->file_id=$file->id;
            $content->save();
        }
        return ['file_name'=>$name,'file_id'=>$file->id];
    }

我的模型是撰稿人,并且内容替换为您的模型.

My Models is Copywriter and Content replace it with your's.