【问题标题】:Utilities base64Encode versus base64Decode method实用程序 base64 编码与 base64 解码方法
【发布时间】:2015-12-27 22:00:52
【问题描述】:

为什么 base64Decode 不能解码 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);
}

此 google 应用程序脚本从现有的 google 驱动器源文件中检索字节并将这些字节转换为 base64 编码字符串 (base64EncodedBytes)。然后它将字符串转换回普通字节数组,并在同一文件夹中创建一个全新的文件。

现在,如果我们在 Google Drive 中查看最终结果,我们可以看到复制的文件(后缀为“.copy.png”的文件)的大小不同并且已损坏。

这种编码/解码 API 使用有什么问题?

【问题讨论】:

    标签: google-apps-script base64 decode utilities


    【解决方案1】:

    在没有字符集的情况下对文件进行编码。当您对字符串进行编码时,字符集是有意义的,但对于文件(如本例),您应该对其进行编码并解码为“一般”的东西。
    试试:

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

    Utilities.base64Decode(base64EncodedBytes);
    

    看看它是否适合你。

    【讨论】:

      猜你喜欢
      • 2017-08-13
      • 2015-07-14
      • 2014-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      • 1970-01-01
      相关资源
      最近更新 更多