Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a zip file inside Google Drive with Apps Script

I have a folder in Google Drive folder containing few files. I want to make a Google Apps Script that will zip all files in that folder and create the zip file inside same folder.

I found a video that has Utilities.zip() function, but there is no API reference for that. How do I use it? Thanks in advance.

like image 613
Lolitha Ratnayake Avatar asked Nov 06 '12 20:11

Lolitha Ratnayake


People also ask

Can you make a zip file on Google Drive?

You can compress one file, or multiple files at once! In Google Drive, select the files/folders you would like to include in your compresse file. You can see the progess on the bottom right side of your browser. After it's done, a compressed .

How do I create a zip folder in Google Drive?

Drag files into Google Drive On your computer, go to drive.google.com. Open or create a folder. To upload files and folders, drag them into the Google Drive folder.

Does Google Drive automatically zip files?

Google will automatically zip a folder or multiple files when you try to download them from your Google Drive.


1 Answers

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

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'));
like image 159
Corey G Avatar answered Sep 21 '22 08:09

Corey G