Reputation: 2477
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?
Upvotes: 4
Views: 9777
Reputation: 3845
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.
Upvotes: 8