Creating a zip file inside Google Drive with Apps Script

前端 未结 4 1346
深忆病人
深忆病人 2020-11-30 05:26

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 f

4条回答
  •  無奈伤痛
    2020-11-30 05:58

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

提交回复
热议问题