Creating a zip file inside Google Drive with Apps Script

前端 未结 4 1347
深忆病人
深忆病人 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:41

    As DocsList has been deprecated, You can use the following code to zip an entire folder containing files and sub-folders and also keep its structure:

    var folder = DriveApp.getFolderById('');
    var zipped = Utilities.zip(getBlobs(folder, ''), folder.getName()+'.zip');
    folder.getParents().next().createFile(zipped);
    
    function getBlobs(rootFolder, path) {
      var blobs = [];
      var files = rootFolder.getFiles();
      while (files.hasNext()) {
        var file = files.next().getBlob();
        file.setName(path+file.getName());
        blobs.push(file);
      }
      var folders = rootFolder.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(getBlobs(folder, fPath));
      }
      return blobs;
    }
    

    getBlobs function makes an array of all files in the folder and changes each file name to it's relative path to keep structure when became zipped.

    To zip a folder containing multiple items with the same name use this getBlob function:

    function getBlobs(rootFolder, path) {
      var blobs = [];
      var names = {};
      var files = rootFolder.getFiles();
      while (files.hasNext()) {
        var file = files.next().getBlob();
        var n = file.getName();
        while(names[n]) { n = '_' + n }
        names[n] = true;
        blobs.push(file.setName(path+n));
      }
      names = {};
      var folders = rootFolder.getFolders();
      while (folders.hasNext()) {
        var folder = folders.next();
        var n = folder.getName();
        while(names[n]) { n = '_' + n }
        names[n] = true;
        var fPath = path+n+'/';
        blobs.push(Utilities.newBlob([]).setName(fPath)); //comment/uncomment this line to skip/include empty folders
        blobs = blobs.concat(getBlobs(folder, fPath));
      }
      return blobs;
    }
    

提交回复
热议问题