Search code examples
google-apps-scriptgoogle-drive-apizipdirectory-structure

How to create a zip from an array of Blobs with a folder structure


I get how to create a zip from an array of Blobs, but is it somehow possible to define a folder structure within the zip itself?

for example.. archive/img/file1.jpg


Solution

  • Yes, although it's not readily apparent.

    First, it's important to understand that the Blob objects in Google App Scripts are a little different than JavaScript's normal Blob objects. The most important difference is that they have a name, and many parts of the API use this name. (Including Utilities.zip())

    Utilities.zip() treats the name on a blob as a pathname, so you can build entire hierarchies by just including slashes:

    //Create a test blob
    var blob = Utilities.newBlob("My Data");
    blob.setName("foo/bar.txt");
    //Should be a zip containing a folder named "foo", which contains a file named "bar.txt", which has the contents "My Data"
    var zipBlob = Utilities.zip([blob], "test.zip");