2015-12-27 32 views
0

爲什麼base64Decode無法解碼剛剛由base64Encode編碼的東西?實用程序base64Encode與base64Decode方法

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); 
} 

此谷歌應用腳​​本從現有的谷歌驅動源文件中檢索字節和這些字節轉換爲base64編碼串(base64EncodedBytes)。然後它將字符串轉換回正常字節數組,並在同一個文件夾上創建一個全新的文件。

現在,如果我們看看最終的結果到谷歌驅動器,我們可以看到複製的文件(帶有後綴「.copy.png」)不具有相同的尺寸和被損壞。

有什麼不對的編碼/解碼API的使用?

回答

1

編碼沒有字符集的文件。當字符串編碼時,charset是有意義的,但是在文件的情況下(比如在這種情況下),你應該對它進行編碼並解碼爲「一般」的東西。
嘗試:

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

Utilities.base64Decode(base64EncodedBytes); 

,看看它是否適合你。