简体   繁体   中英

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; 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]);]

    //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. unZippedfile.length is the number of files in the zip file. Use a loop around the createFile method.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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