且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用apps脚本在Google Drive中创建一个zip文件

更新时间:2023-12-04 21:02:16

其实它比这更简单。文件已经是Blob(任何具有getBlob()的文件都可以传递给任何需要Blob的函数)。所以代码如下所示:

Actually it's even easier than that. Files are already Blobs (anything that has getBlob() can be passed in to any function that expects Blobs). So the code looks like this:

var folder = DocsList.getFolder('path/to/folder');
folder.createFile(Utilities.zip(folder.getFiles(), 'newFiles.zip'));

另外,如果您在文件夹中有多个具有相同名称的文件,它将不起作用。 。谷歌云端硬盘文件夹支持,但Zip文件不支持。

Additionally, it won't work if you have multiple files with the same name in the Folder... Google Drive folders support that, but Zip files do not.

为了使这个工作可以使用多个同名的文件:

To make this work with multiple files that have the same name:

var folder = DocsList.getFolder('path/to/folder');
var names = {};
folder.createFile(Utilities.zip(folder.getFiles().map(function(f){
  var n = f.getName();
  while (names[n]) { n = '_' + n }
  names[n] = true;
  return f.getBlob().setName(n);
}), 'newFiles.zip'));