从Google Drive大量下载经过身份验证的文件

问题描述 投票:0回答:1

我在 Google 云端硬盘的共享文件夹中有数千个文件,我无法完全控制这些文件。我需要将它们下载到配备足够内存和CPU的服务器上进行分析。

我想出了一个解决方案,首先打印文件 ID,然后使用 gdown 一次下载一个。请参阅下面的评论。

google-apps-script google-drive-api
1个回答
0
投票

访问 https://script.new/ 并登录 Google。这样就解决了身份验证问题。

单击屏幕左侧“库”旁边的“加号”按钮。输入脚本 ID

1HLv6tWz0oXFOJHerBTP8HsNmhpRqssijJatC92bv9Ym6HSN69_UuzcDk
并继续安装库 BatchRequest

单击屏幕左侧“服务”旁边的“加号”按钮。选择“Drive API”并继续启用 Drive API 服务。我的案例采用了 v3。

将以下代码片段复制到您的脚本中。您唯一需要输入的是您的文件夹 ID,它是您的文件夹链接的后缀,其中有要下载的文件。

function myFunction() {
  const sourceFolderId = "";  // Please set the source folder ID. This is something like 18b0tVyn4ErDOSKhaOKD4vZSIDB2tl
    
  const getFiles = (id, res = []) => {
    const folder = DriveApp.getFolderById(id);
    const files = folder.getFiles();
    while (files.hasNext()) {
      const file = files.next();
      res.push({name: file.getName(), id: file.getId()})
    }
    let ids = [];
    const folders = folder.getFolders();
    while (folders.hasNext()) ids.push(folders.next().getId());
    if (ids.length > 0) ids.forEach(id => getFiles(id, res));
    return res;
  }

  const files = getFiles(sourceFolderId);
  
  // Create a text file
  const fileIdsText = files.map(file => file.id).join("\n");
  const txtFile = DriveApp.createFile('file_ids.txt', fileIdsText);
  console.log('File IDs saved to: ' + txtFile.getUrl());
}

执行后,您可能会在日志中发现一条消息,提示您的文件ID存储在您自己的Google Drive中的

file_ids.txt
中,其中每一行包含一个文件ID,对应于您的目标文件夹中的一个文件。

对于Linux用户,安装gdown并参考文件ID执行以下shell脚本进行下载:

#!/bin/bash

while IFS= read -r file_id
do
    download_url="https://drive.google.com/uc?id=${file_id}"
    gdown "$download_url"
done < ids.txt

echo "File download completed."
© www.soinside.com 2019 - 2024. All rights reserved.