简体   繁体   English

Google Apps 脚本解压文件 - 问题

[英]Google Apps Script Unzipping Files - Issues

I have a script that looks in a destination folder and unzips files to a new folder.我有一个在目标文件夹中查找并将文件解压缩到新文件夹的脚本。 All works perfect as long as the zip contains just one file;只要 zip 只包含一个文件,一切都完美无缺; anymore and I only seem to unzip the first file.不再,我似乎只解压缩了第一个文件。

Im pretty sure the line that's causing this is which is picking the first record in the array of files however I am not quite skilful enough to figure out how to get around this.我很确定导致这种情况的行是选择文件数组中的第一条记录,但是我不够熟练,无法弄清楚如何解决这个问题。 Any help would be greatly appreciated任何帮助将不胜感激

[var newDriveFile = DestinationFolder.createFile(unZippedfile[0]);] [var newDriveFile = DestinationFolder.createFile(unZippedfile[0]);]

    //Unzips all ZIP files in the folder
function Unzip() {
  //Add folder ID to select the folder where zipped files are placed
  var SourceFolder = DriveApp.getFolderById("14vRNV3FZJicplxeurycsfBHmETrUQBex")
  //Add folder ID to save the where unzipped files to be placed
  var DestinationFolder = DriveApp.getFolderById("1OJXkPrUqcqapsv366oCV_ZsvaECstKTn")
  //Select the Zip files from source folder using the Mimetype of ZIP
  var ZIPFiles = SourceFolder.getFilesByType(MimeType.ZIP)
  //var ZIPFiles = SourceFolder.getFilesByName('MTTR.zip')
  
  //Loop over all the Zip files
  while (ZIPFiles.hasNext()){
   // Get the blob of all the zip files one by one
    var fileBlob = ZIPFiles.next().getBlob();
   //Use the Utilities Class to unzip the blob
    var unZippedfile = Utilities.unzip(fileBlob);
   //Unzip the file and save it on destination folder
    var newDriveFile = DestinationFolder.createFile(unZippedfile[0]); //I think this line is where my issue is

    }
Logger.log("Finished Unzipping files")
}

As what Rodrigo mentioned in the comments, you need to loop it on all the files.正如 Rodrigo 在评论中提到的,您需要在所有文件上循环它。 unZippedfile.length is the number of files in the zip file. unZippedfile.length是 zip 文件中的文件数。 Use a loop around the createFile method.使用围绕createFile方法的循环。

Code:代码:

// loop to all zip files
while (ZIPFiles.hasNext()){
  var fileBlob = ZIPFiles.next().getBlob();
  var unZippedfile = Utilities.unzip(fileBlob);
  // loop to all items inside the current zip file
  for (i=0; i<unZippedfile.length; i++) {
    var newDriveFile = DestinationFolder.createFile(unZippedfile[i]); 
  }
}

Output:输出:

输出

Note:笔记:

  • Sample output above show the unzipped files on the same directory as I instantiated both source and destination with the same directory ID.上面的示例输出显示了相同目录中的解压缩文件,因为我使用相同的目录 ID 实例化了源和目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM