Search code examples
google-apps-scriptgoogle-drive-apigoogle-apps

How to add/append string to blob in Google Apps Script (Google Drive API)


This code does work, except this part Drive.Files.update(thefile, theFileID, updatedBlob);

var folder = DriveApp.getFolderById("0B0RcUNcUERU5MGpIaEXXXXXXXX");
var file = DriveApp.getFileById("NcUERXXXXXXXXERU5UWQUTZKY2X2"); 
var file2 = DriveApp.getFileById("NcUERXXXXXXXXERU5UWDDDDDDD2"); 

var myString = "sometext";
var updatedBlob = file.getBlob() + myString;

var myFileName = "StringAddedFile.mp4";  
var thefile = {
  title: myFileName,
  mimeType: 'video/mp4'
};

var allFilesByName = folder.getFilesByName(myFileName);
while (allFilesByName.hasNext()) {
  var thisFile = allFilesByName.next();
  var theFileID = thisFile.getId();
  var myVar = Drive.Files.update(thefile, theFileID, updatedBlob);
};

I have tried:

file.getBlob() + myString;
file.getBlob().getDataAsString() + myString;
file.getBlob().getDataAsString() + file2.getBlob().getDataAsString();
file.getAs() + file2.getAs();
file.getBlob() + file2.getBlob();

...

Getting this error message: "The mediaData parameter only supports Blob types for upload."

How can I add/append myString to file?


Solution

  • It looks like you are trying to add something to a mimeType: 'video/mp4' file. It looks like you need to create a blob from the string. You can use the Utilities service to do that.

    For String

    • Create a base 64 encoded string
    • encoded string as a byte array

    For file

    • Get file as blob
    • Convert blob to bytes

    Combine

    • Combine bytes of both files
    • Update file as blob with another blob

    The code:

    var myString = "sometext";
    var encoded = Utilities.base64Encode(myString);
    var byteDataArray = Utilities.base64Decode(encoded);
    
    var file = DriveApp.getFileById("File ID here");
    var fileAsBlob = file.getBlob();
    var fileAsBytes = fileAsBlob.getBytes();
    
    var combinedBytes = byteDataArray.concat(fileAsBytes);
    var allBytesAsBlob = Utilities.newBlob(combinedBytes);
    
    var updatedBlob = Drive.Files.update(thefile, theFileID, allBytesAsBlob);
    

    This is a suggestion to try. Haven't tested it. Don't know if it will work, but no-one else has answered, so can't hurt to try. I'll leave it up to you to try, and let me know if it works or not.