簡體   English   中英

在根目錄下創建文件夾並將文件上傳到該文件夾​​google drive api

[英]Create folder in root directiry of and upload file to that folder google drive api

我想使用CURL在googledrive根目錄中創建文件夾。 文件已上傳到驅動器,但是我需要創建一個文件夾並將文件上傳到該文件夾​​。

根據@hanshenrik代碼創建文件夾的工作移動文件不工作

我更新的代碼:

$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 );
}

https://developers.google.com/drive/api/v2/folder上查看文件夾中的文檔,似乎您是通過將內容類型設置為application/vnd.google-apps.folder的空“文件”上傳來創建文件夾的application/vnd.google-apps.folder

以下是有關如何以簡單方式上傳文件的文檔: https : //developers.google.com/drive/api/v2/simple-upload

上載方法的問題在於,創建的文件(在這種情況下為文件夾)將沒有名稱,它只會被命名為untitled<whatever> ,因此,最后,這是有關如何重命名文件的文檔: https:// developers.google.com/drive/api/v3/reference/files/update (在這種情況下為文件夾)

放在一起,您可能最終會得到類似以下內容的結果:

<?php
$ch = curl_init ();
curl_setopt_array ( $ch, array (
        CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files?uploadType=media',
        CURLOPT_HTTPHEADER => array (
                'Content-Type: application/vnd.google-apps.folder',
                'Authorization: Bearer '.getAccessToken ( $credentials )  
        ),
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => '', // "empty file"
        CURLOPT_RETURNTRANSFER => 1 
) );
try {
    // this will create the folder, with no name
    if (false === ($resp = curl_exec ( $ch ))) {
        throw new \RuntimeException ( 'curl error ' . curl_errno ( $ch ) . ": " . curl_error ( $ch ) );
    }
    $parsed = json_decode ( $resp, true );
    if (! $parsed || $parsed ['code'] !== 200) {
        throw new \RuntimeException ( 'google api error: ' . $resp );
    }
    $id = $parsed ['id'];
    // now to give the folder a name:
    curl_setopt_array ( $ch, array (
            CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files/' . urlencode ( $id ),
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => json_encode ( array (
                    'name' => 'the_folders_name' 
            ) ),
            CURLOPT_CUSTOMREQUEST => 'PATCH',
            CURLOPT_HTTPHEADER => array (
                    'Content-Type : application/json',
                    'Authorization: Bearer ' . getAccessToken ( $credentials ) 
            ) 

    ) );

    if (false === ($resp = curl_exec ( $ch ))) {
        throw new \RuntimeException ( 'curl error ' . curl_errno ( $ch ) . ": " . curl_error ( $ch ) );
    }
    $parsed = json_decode ( $resp, true );
    if (! $parsed || $parsed ['code'] !== 200) {
        throw new \RuntimeException ( 'google api error: ' . $resp );
    }
} finally{
    curl_close ( $ch );
}
var_dump ( $resp );

最后,要在此文件夾中移動文件,請將PATCH請求發送到https://www.googleapis.com/upload/drive/v3/files/<file_you_want_to_move_id> ,其中文件夾的ID為請求正文的addParents參數,例如就像是:

<?php
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_POSTFIELDS => json_encode ( array (
                    'addParents' => $folder_id,
                    'removeParents'=> 'root',


            ) ),
            CURLOPT_CUSTOMREQUEST => 'PATCH',
            CURLOPT_HTTPHEADER => array (
                    'Content-Type : application/json',
                    'Authorization: Bearer ' . getAccessToken ( $credentials ) 
            ) 

    ) );
    if (false === ($resp = curl_exec ( $ch ))) {
        throw new \RuntimeException ( 'curl error ' . curl_errno ( $ch ) . ": " . curl_error ( $ch ) );
    }
    $parsed = json_decode ( $resp, true );
    if (! $parsed || $parsed ['code'] !== 200) {
        throw new \RuntimeException ( 'google api error: ' . $resp );
    }
} finally{
    curl_close ( $ch );
}

這將對您有幫助:

https://developers.google.com/drive/api/v3/folder

創建一個文件夾:

在Drive API中,文件夾本質上是一個文件-由特殊文件夾MIME類型application / vnd.google-apps.folder標識。 您可以通過插入具有此MIME類型的文件和文件夾標題來創建新文件夾。 設置文件夾標題時不包括擴展名。

$fileMetadata = new Google_Service_Drive_DriveFile(array(
    'name' => 'Invoices',
    'mimeType' => 'application/vnd.google-apps.folder'));
$file = $driveService->files->create($fileMetadata, array(
    'fields' => 'id'));
printf("Folder ID: %s\n", $file->id);

在文件夾中插入文件:

要將文件插入特定文件夾,請在文件的parents屬性中指定正確的ID,如下所示:

$folderId = '0BwwA4oUTeiV1TGRPeTVjaWRDY1E';
$fileMetadata = new Google_Service_Drive_DriveFile(array(
    'name' => 'photo.jpg',
    'parents' => array($folderId)
));
$content = file_get_contents('files/photo.jpg');
$file = $driveService->files->create($fileMetadata, array(
    'data' => $content,
    'mimeType' => 'image/jpeg',
    'uploadType' => 'multipart',
    'fields' => 'id'));
printf("File ID: %s\n", $file->id);

在創建文件夾以及創建子文件夾時,可以使用parents屬性。

在文件夾之間移動文件:要添加或刪除現有文件的父項,請在文件上使用addParents和removeParents查詢參數。 更新方法。

可以使用這兩個參數將文件從一個文件夾移動到另一個文件夾,如下所示:

$fileId = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
$folderId = '0BwwA4oUTeiV1TGRPeTVjaWRDY1E';
$emptyFileMetadata = new Google_Service_Drive_DriveFile();
// Retrieve the existing parents to remove
$file = $driveService->files->get($fileId, array('fields' => 'parents'));
$previousParents = join(',', $file->parents);
// Move the file to the new folder
$file = $driveService->files->update($fileId, $emptyFileMetadata, array(
    'addParents' => $folderId,
    'removeParents' => $previousParents,
    'fields' => 'id, parents'));

這是我的工作示例:

要連接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];
    }

我的模特是撰稿人內容已替換為您的。

看到它是否正常。 我進行了更改,例如"name" => ""CURLOPT_CUSTOMREQUEST => 'POST',

function CreateGDFolder($credentials)
    {
        $ch = curl_init();
        curl_setopt_array ( $ch, array (
        CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files',
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => json_encode ( array (
            // Earlier it was title changed to name
            "name" => "pets",
            "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($ch);
        $response = json_decode($response, true);
        print_r($response); 
        curl_close($ch);
    }

看到它對我很好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM