Google AppsScript中的Base64编码(字节)数组?

时间:2016-11-23 04:30:13

标签: arrays google-apps-script base64 byte

在Google AppsScript中,我尝试Base64 encode使用Utilities类的字节数组。

更新:此示例:https://script.google.com/d/15eLqgLHExpLG64JZhjUzKfBj4DgLhNZGBOkjwz7AkeeUbcgcaraP4y9X/edit?usp=sharing

// bytes to encode
var toenc = [ 0x52 , 0x49 , 0x46 , 0x46 
        , 0xBC , 0xAF , 0x01 , 0x00 
        , 0x57 , 0x41 , 0x56 , 0x45 
        , 0x66 , 0x6D , 0x74 , 0x20 
        , 0x10 , 0x00 , 0x00 , 0x00 
        , 0x01 , 0x00 , 0x01 , 0x00 
        , 0x40 , 0x1f , 0x00 , 0x00 
        , 0x40 , 0x1f , 0x00 , 0x00 
        , 0x01 , 0x00 , 0x08 , 0x00 
        , 0x64 , 0x61 , 0x74 , 0x61 
        , 0x98 , 0xaf , 0x01 , 0x00
];

// This errs with -- Cannot convert Array to (class)[]
Logger.log(Utilities.base64EncodeWebSafe(toenc));

// OK, typing issue?  Following the doc, but still get same error :-(
Logger.log(Utilities.base64EncodeWebSafe(
  Utilities.newBlob(toenc).getBytes()
));

唉,同样的错误运行时无法将数组转换为(类)[]

如果我有一个(字节)数字数组(实际上是一个字符串),我可以将Utilities类用于Base64吗?

2 个答案:

答案 0 :(得分:1)

以下脚本对您有帮助吗?如果我误解了你的问题,我道歉。

var toenc = [ 0x57 , 0x41 , 0x56 , 0x45 
  , 0x66 , 0x6D , 0x74 , 0x20 
  , 0x10 , 0x00 , 0x00 , 0x00 
  , 0x64 , 0x61 , 0x74 , 0x61
];
var a1 = Utilities.base64EncodeWebSafe(toenc);
var a2 = Utilities.base64DecodeWebSafe(a1, Utilities.Charset.UTF_8);
var a3 = Utilities.newBlob(a2).getDataAsString();

>>> a1 = V0FWRWZtdCAQAAAAZGF0YQ==
>>> a2 = [87, 65, 86, 69, 102, 109, 116, 32, 16, 0, 0, 0, 100, 97, 116, 97]
>>> a3 = WAVEfmt ���data

答案 1 :(得分:0)

找到答案。它处理的是该函数需要2的恭维数。解决方案:

function to64(arr) {
  var bytes = [];
  for (var i = 0; i < arr.length; i++) 
    bytes.push(arr[i]<128?arr[i]:arr[i]-256);
  return Utilities.base64EncodeWebSafe(bytes)
} // to64

https://stackoverflow.com/a/20639942/199305