Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
915 views
in Technique[技术] by (71.8m points)

google apps script - Converting string to web-safe Base64 format

I am testing how to update user picture using the Admin SDK Directory Service with Google Apps Scripts with the following function:

function updatePhoto(){
  var fileId = 'XXXXXXXXXXXXXXXXXXX';
  var b = DocsList.getFileById(fileId).getBlob();
  var encoded = Utilities.base64Encode(b.getBytes());

  encoded = encoded.replace(///g,'_').replace(/+/g,'-').replace(/=/g,'*');
  AdminDirectory.Users.Photos.update({
    "photoData": encoded },'harry.potter@abc.edu.hk');
}

However, it doesn't always work. Whenever there is padding in the base64 encoded string, it fails. Referring to Google's document (https://developers.google.com/admin-sdk/directory/v1/reference/users/photos/update), I am a bit confused with the descriptions. It says:

  1. The equals sign (=) character is replaced with the asterisk (*).
  2. For padding, the period (.) character is used instead of the RFC-4648 baseURL definition which uses the equals sign (=) for padding. This is done to simplify URL-parsing.

What should be actually done? (=) is used for padding in Base64. So, should I use (*) or (.)? I did try to replace (=) with (.) but no luck.

Can anyone help?


It is so strange. It works when i do not replace (=).

function updatePhoto(){
  var fileId = 'XXXXXXXXXXXXXXXXXXX';
  var b = DocsList.getFileById(fileId).getBlob();
  var encoded = Utilities.base64Encode(b.getBytes());

  encoded = encoded.replace(///g,'_').replace(/+/g,'-');
  AdminDirectory.Users.Photos.update({
    "photoData": encoded },'harry.potter@abc.edu.hk');

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The API requires you to use URL-safe base64 encoding. After doing the base64 encoding, try replacing / with _ and + with -. Details at:

https://developers.google.com/admin-sdk/directory/v1/reference/users/photos/update


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...