簡體   English   中英

使用 Google Drive 上傳文件夾中的文件 API

[英]Upload Files In Folders Using Google Drive API

我目前有以下代碼可以成功地將文件上傳到根目錄中的谷歌驅動器。 我將如何更改以下代碼,以便如果$folderName存在,它會上傳該文件夾下的文件,但如果$folderName不存在,它會創建文件夾,將其命名為$folderName ,然后在其下添加文件。

function uploadFiles($filePath, $fileName, $folderName) {
    $file = new Google_Service_Drive_DriveFile();
    $file->setName($fileName);
    $file->setDescription('A test document');
    
    $data = file_get_contents($filePath);
    
    $createdFile = $this->service->files->create($file, array(
        'data' => $data,
        'uploadType' => 'multipart'
    ));
}

我相信你的目標和情況如下。

  • 您想使用 googleapis 將文件上傳到 php 的特定文件夾。
  • 當特定文件夾不存在時,您要創建文件夾並將文件上傳到該文件夾。
  • 當特定文件夾存在時,您希望將文件上傳到該文件夾。
  • 您已經能夠使用 Drive API 將文件上傳到 Google Drive。

修改點:

  • 在這種情況下,首先需要確認特定文件夾是否存在。 所以在這種情況下,使用驅動器API中的“文件:列表”的方法。 所以修改后的腳本流程如下。

    1. 使用文件夾名稱搜索現有文件夾。
    2. 當文件夾名稱的文件夾不存在時,按文件夾名稱創建文件夾,並返回創建文件夾的文件夾ID。
      • 在這種情況下,使用“文件:創建”的方法。
    3. 當文件夾名稱的文件夾存在時,返回文件夾 ID。
    4. 使用文件夾 ID 將文件上傳到文件夾。

修改后的腳本:

function uploadFiles($filePath, $fileName, $folderName) {
    // 1. Search the existing folder using the folder name.
    $res = $this->service->files->listFiles(array("q" => "name='{$folderName}' and trashed=false"));
    $folderId = '';
    if (count($res->getFiles()) == 0) {
        // 2. When the folder of the folder name is NOT existing, the folder is created by the folder name and the folder ID of the created folder is returned.
        $file = new Google_Service_Drive_DriveFile();
        $file->setName($folderName);
        $file->setMimeType('application/vnd.google-apps.folder');
        $createdFolder = $this->service->files->create($file);
        $folderId = $createdFolder->getId();
    } else {
        // 3. When the folder of the folder name is existing, the folder ID is returned.
        $folderId = $res->getFiles()[0]->getId();
    }

    // 4. The file is uploaded to the folder using the folder ID.
    $file = new Google_Service_Drive_DriveFile();
    $file->setName($fileName);
    $file->setDescription('A test document');
    $file->setParents(array($folderId));
    $data = file_get_contents($filePath);
    $createdFile = $this->service->files->create($file, array(
        'data' => $data,
        'uploadType' => 'multipart'
    ));
}

參考:

暫無
暫無

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

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