Download Folder as Zip Google Drive API

眉间皱痕 提交于 2021-01-28 10:52:58

问题


I currently have a Google App Script in Google Sheet that gives me the URL of a folder, which I can then use to download. Though it is an extra step I would like to remove, and get the URL of the zipped content directly.

Here's my code (google app script):

function downloadSelectedScripts() {
  // ...
  var scriptFiles = getScriptFiles(scriptFileNames)
  var tempFolder = copyFilesToTempFolder(scriptFiles)
  Browser.msgBox(tempFolder.getUrl())
}

function copyFilesToTempFolder(files) {
  var tempFolder = DriveApp.getFolderById(FOLDERS.TEMP)
  var tempSubFolder = tempFolder.createFolder('download_' + Date.now())

  for (var i in files) {
    var file = files[i]
    file.makeCopy(file.getName(), tempSubFolder)
  }

  return tempSubFolder
}

回答1:


  • You want to compress all files in a folder as a zip file.
    • The folder has no subfolders.
    • All files are only text files.
    • The total size of all files is less than 50 MB.
  • You want to retrieve the URL for downloading the zip file.

If my understanding is correct, how about this sample script? The flow of this script is as follows.

  1. Retrieve folder.
  2. Retrieve blobs of all files in the folder.
  3. Compress blobs and retrieve a blob of zip.
  4. Create a zip blob as a file.
  5. Retrieve URL for downloading.

Sample script:

When you use this script, please set the folder ID of folder that you want to compress.

function myFunction() {
  var folderId = "###"; // Please set the folder ID here.

  var folder = DriveApp.getFolderById(folderId);
  var files = folder.getFiles();
  var blobs = [];
  while (files.hasNext()) {
    blobs.push(files.next().getBlob());
  }
  var zipBlob = Utilities.zip(blobs, folder.getName() + ".zip");
  var fileId = DriveApp.createFile(zipBlob).getId();
  var url = "https://drive.google.com/uc?export=download&id=" + fileId;
  Logger.log(url);
}

Result:

The direct link of the zip file is returned as follows.

https://drive.google.com/uc?export=download&id=###

Note:

  • In the current stage, unfortunately, the folders cannot be included in the zip data with Google Apps Script.
  • In this sample script, the filename of zip file is the folder name. So please modify it for your situation.
  • If you want to download the zip file without login to Google, please share the file.

Reference:

  • zip(blobs, name)


来源:https://stackoverflow.com/questions/56297366/download-folder-as-zip-google-drive-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!