3
votes

I would like to make a script for Google Drive. I want to make a weekly backup of my folders and store them in another folder in Google Drive. About the weekly trigger, I've got that OK, but I'm having problems because I can't find a way to zip an entire folder. The folders that I want to zip have multiple subfolders and documents. I've tried searching in each folder and making a zip of the files, but I find it complicated and I end up with many zip files for one folder. The code that I have so far is this:

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

And I receive in error that it can't zip a folder, it has to be a blob. How can I fix this?

Thanks!

1

1 Answers

1
votes

You can use this code:

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;
}