簡體   English   中英

如何使用 JS API 將文件上傳到 Google 雲端硬盤中的特定位置?

[英]How to upload a file into a specific location in the Google Drive using the JS API?

我正在使用googleapis將不同的文件上傳到 Google 雲端硬盤。 場景是:

  1. 用戶通過我的 REST API(我正在使用 NodeJS)提供文檔及其信息。
  2. REST API 創建將包含該文檔的目錄(如果它尚不存在)。
  3. REST API 將文檔上傳到該目錄。

驅動結構如下:

/root/documents/$type/$new_document

其中$type是用戶提供的字段之一, $new_document是用戶提供的文檔。

我的連接方式:

oauth2Client.setCredentials({ refresh_token: REFRESH_TOKEN });
drive_instance = google.drive({
  version: 'v3',
  auth: oauth2Client,
});

我想出了如何將文檔上傳到 Google 雲端硬盤的文件夾:

}
try {
    const response = await drive.files.create({
      requestBody: {
        name: file.name,
        mimeType: file.mimetype,
      },
      media: {
        mimeType: file.mimetype,
        body: file.data,
      },
    });

    console.log(response.data);
} catch (error) {
    console.log(error.message);
}

我正在努力的是:

  1. 如果目錄/root/documents/$type不存在,如何創建它?
  2. 如何將$new_document上傳到/root/documents/$type

對於第二個問題,我知道文檔提供了一個包含所有文件夾 ID 的parents[]選項。 但是,我怎樣才能得到/root/documents/$type的文件夾 ID? 有沒有辦法組合這些步驟(比如mkdir -p目錄或創建目錄將返回目錄的 ID)。

1.嘗試通過drive.files.list()方法找到你需要的文件夾

您需要設置過濾器。 例子:

在 requestBody 中添加'q': "..."以搜索您需要的內容

使用"name = 'Some Folder Name'"按名稱搜索

使用"mimeType = 'application/vnd.google-apps.folder'"僅搜索文件夾

因此,通過and組合:

'q': "name = 'Some Folder Name' and mimeType = 'application/vnd.google-apps.folder'"查找具有您選擇的名稱的所有文件夾

const folderName = 'Some Folder Name'


gapi.client.drive.files
                .list({
                    'q': "name = 'Some Folder Name' and mimeType = 'application/vnd.google-apps.folder'",
                    'pageSize': 1000,
                    'fields': "files(id, name, parents)"
                })
                .then((response) => {

                    const files = response.result.files;
                    if (files.length > 0) {
                      handleSearchResult(files)
                    } else {
                      createFolder()
                    }
                    console.log(total / (1024*1024*1024))
                });

關於handleSearchResult()createFolder

  • 它可能超過 1 個文件。 所以你可以找到必要的 root 獲取files[i].parents 這就是為什么我在'fields': "files(id, name, parents)"中添加了parents :“files(id, name, parents)”。 https://developers.google.com/drive/api/v3/reference/files
  • 您也可以添加搜索規則,例如'parents contain "..."'' https://developers.google.com/drive/api/v3/search-files
  • 如果搜索結果為 0 個文件,請自行創建文件夾。 您可以逐步創建路徑\目錄。 在驅動器根目錄中創建第一個文件夾並記住id 之后創建第二個文件夾並添加 requestBody parentId等於第一個文件夾id 等等...順便說一句,您可以使用幾乎相同的邏輯進行搜索。

2. 必要時創建文件夾

例子:

// name = 'Folder Name', 
// parents = ['some-parent1-id', 'some-parent2-id', ...]
function createFolder(name, parents) {
            const fileMetadata = {
                'name' : name,
                'mimeType' : 'application/vnd.google-apps.folder',
                'parents': parents
            };
            gapi.client.drive.files
                .create({
                    resource: fileMetadata,
                }).then((response) => {
                    switch(response.status){
                        case 200:
                            const file = response.result;

                            console.log('Created Folder Id: ' + file.id);
                            break;
                        default:
                            console.log('Error creating the folder, '+response);
                            break;
                    }
                });
        }

3.上傳文件並設置parents

您應該在requestBody中添加parents = ['id-of-folder']

閱讀更多Google Drive API - 文件:創建

我希望它至少會有所幫助:)繼續努力!

您可以使用以下方法上傳文件夾內的文件夾

  1. 您應該擁有要在其中存儲新文件夾的文件夾的 ID (可以使用 nodejs api 或通過打開文件夾並查看 url 中 last / 之后的字符來提取)
  2. 使用為谷歌驅動器中的文件夾保留的特殊 mimetype ( application/vnd.google-apps.folder )

考慮你的例子

drive.files.create({
  requestBody:{
    name:"SomeFolder",
    mimeType:"application/vnd.google-apps.folder"
  },(error,folder)=>{
    console.log(folder.data.id);
    drive.files.create:({
       requestBody:{
       name:"SomeFolderInsideAFolder",
       mimeType:"application/vnd.google-apps.folder"
       },
       parents:[folder.data.id]
    })
 })
})

您甚至可以通過文件上傳和文件夾上傳相結合輕松創建遞歸上傳文件夾function,可以上傳整個文件夾

暫無
暫無

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

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