user1464409
user1464409

Reputation: 1042

How do you update a zip in Google Apps Script?

I am trying to update a zip file in Google Apps Script but I cannot seem to get it to work.

Here is the extract of code that is causing the problem:

var filenameToGet = filename+'.zip';
var theFilesRetrieved = folder.getFilesByName(filenameToGet);
if (theFilesRetrieved.hasNext() === false) {
    // if no file is found then create it
    folder.createFile( Utilities.zip([ fileXYZ ], filename+'.zip') );
} else {
    while (theFilesRetrieved.hasNext()) {
        var fileZIP = theFilesRetrieved.next();
        fileZIP.setContent( Utilities.zip([ fileXYZ ]).getBytes() );
    }
}

If "filename.zip" does not exist the script correctly creates the zip file.

If "filename.zip" does exist the file created is corrupt. These leads me to believe it is this line that is wrong:

fileZIP.setContent( Utilities.zip([ fileXYZ ]).getBytes() );

I have tried .getDataAsString() and just Utilities.zip([ fileXYZ ]) as well but these also creates a corrupt zip file.

(fileXYZ is a file blob).

How do I update the contents of a zip file that alreadys exists?

Upvotes: 1

Views: 773

Answers (1)

user3717023
user3717023

Reputation:

The method setContent expects a string as its argument. This is suitable for text files, but not for binary files like zip archives.

In order to overwrite the contents of a binary file, one needs Advanced Drive Service (which must be enabled before use), as Sandy Good explained here. Specifically, use Drive.Files.update, passing metadata object as the first argument, file Id as the second argument, and a blob as the third.

Drive.Files.update({mimeType: 'application/zip'}, fileZIP.getId(), Utilities.zip([fileXYZ]));  

Same within the context of your script:

var filenameToGet = filename+'.zip';
var theFilesRetrieved = folder.getFilesByName(filenameToGet);
if (theFilesRetrieved.hasNext() === false) {
    // if no file is found then create it
    folder.createFile( Utilities.zip([ fileXYZ ], filename+'.zip') );
} else {
    while (theFilesRetrieved.hasNext()) {
        var fileZIP = theFilesRetrieved.next();
        Drive.Files.update({mimeType: 'application/zip'}, fileZIP.getId(), Utilities.zip([fileXYZ]));  
    }
}

Upvotes: 1

Related Questions