2016-11-23 68 views
0

在Google AppsScript中,我正在嘗試使用Utilities類的Base64 encode一個字節數組。Google AppsScript中的Base64編碼(字節)數組?

UPDATE:的這個例子在這裏: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嗎?

+1

我可以運行沒有任何問題這一點。輸出結果爲V0FWRWZtdCAQAAAAZGF0YQ == –

+0

AppsScript中的運行無誤嗎? – Xailor

+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

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 
+0

我完全喪失了爲什麼我無法在AppsScript中執行這些操作。 – Xailor

+0

更新:請參閱我上面的更新。爲了簡潔,我將數組縮短了。現在是44歲,不再工作了。 – Xailor