Home > Enterprise >  Google Apps Script Unzipping Files - Issues
Google Apps Script Unzipping Files - Issues

Time:11-13

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")
}

CodePudding user response:

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:

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.
  • Related