Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Utilities base64Encode versus base64Decode method

Why the base64Decode can't decode something just encoded by base64Encode?

function test_base64encoding_decoding() {
  var file = DriveApp.getFileById("<google drive png file id>");

  // Encode file bytes as a string  
  var base64EncodedBytes = Utilities.base64Encode(file.getBlob().getBytes(), Utilities.Charset.UTF_8);

  // Decode string
  var bytes = Utilities.base64Decode(base64EncodedBytes, Utilities.Charset.UTF_8);

  // create new file
  var blob = Utilities.newBlob(bytes, file.getMimeType(), file.getName() + ".copy.png");
  file.getParents().next().createFile(blob);
}

This google app script retrieves bytes from an existing google drive source file and convert these bytes to a base64 encoded string (base64EncodedBytes). It then converts back the string as a normal bytes array and create a brand new file on the same folder.

Now if we look at the final result into Google Drive we can see the copied file (the one with the suffix ".copy.png") does not have the same size and gets corrupted.

What's wrong with this encode/decode API usage?

like image 509
A. Masson Avatar asked Sep 03 '25 04:09

A. Masson


1 Answers

Encode the file without the Charset. The charset makes sense when you are encoding strings, but in the case of a file ( like in this case) you should encode it and decode as something "general".
Try:

Utilities.base64Encode(file.getBlob().getBytes()); 

and

Utilities.base64Decode(base64EncodedBytes);

to see if it works for you.

like image 131
Gerardo Avatar answered Sep 04 '25 18:09

Gerardo