在1个zip中压缩多个文件夹 - Google Drive Scripts

时间:2014-03-06 22:44:17

标签: google-apps-script google-api google-drive-api

我想为Google云端硬盘制作一个脚本。我想每周备份一次我的文件夹并将它们存储在Google云端硬盘中的另一个文件夹中。 关于每周触发器,我已经可以了,但是我遇到了问题,因为我找不到拉链整个文件夹的方法。 我想要压缩的文件夹有多个子文件夹和文档。我已经尝试在每个文件夹中搜索并制作文件的压缩文件,但我发现它很复杂,我最终得到了一个文件夹的许多zip文件。到目前为止,我的代码是:

function zipFolder(pathFolder, filename, destinyPath) {
  var date = Utilities.formatDate(new Date(), "GMT", "ddMMyyyy");
  var destiny = DocsList.getFolder(destinyPath);
  var folder = DriveApp.getFolderById(DocsList.getFolder(pathFolder).getId());
  var zip = Utilities.zip(folder, filename+date+'.zip');
  destiny.createFile(zip);
}

我错误地收到它无法压缩文件夹,它必须是一个blob。我该如何解决这个问题?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用此代码:

function zipFolder(pathFolder, filename, destinyPath) {
  var date = Utilities.formatDate(new Date(), "GMT", "ddMMyyyy");
  var destiny = DocsList.getFolder(destinyPath);
  var folder = DriveApp.getFolderById(DocsList.getFolder(pathFolder).getId());
  var zip = Utilities.zip(getBlobsPath(folder, ''), filename+date+'.zip');
  destiny.createFile(zip);
}

function getBlobsPath(reFolder, path) {
  var blobs = [];
  var files = reFolder.getFiles();
  while (files.hasNext()) {
    var file = files.next().getBlob();
    file.setName(path+file.getName());
    blobs.push(file);
  }
  var folders = reFolder.getFolders();
  while (folders.hasNext()) {
    var folder = folders.next();
    var fPath = path+folder.getName()+'/';
    blobs.push(Utilities.newBlob([]).setName(fPath)); //comment/uncomment this line to skip/include empty folders
    blobs = blobs.concat(getBlobsPath(folder, fPath));
  }
  return blobs;
}