Google 脚本 base64 解码并将文件保存到云端硬盘

Google Script base64 decode and save file to Drive

我在 Google 表格脚本中收到了 base64 编码的图像。我可以通过登录成功生成图像

e.postData.contents

然后使用https://www.base64decode.org/解码生成一个.jpg文件。但是当我尝试在 google 脚本中进行解码并将一个 jpg 文件写入驱动器时,它已损坏。看起来很相似,但是插入了一些替换字符。这是我的代码:

function doPost(e) {
  var decoded = Utilities.base64Decode(e.postData.contents, Utilities.Charset.UTF_8);
  var blob = Utilities.newBlob(decoded);
  DriveApp.createFile('img_'+date+'.jpg', blob.getDataAsString('Windows-1252'), MimeType.JPEG);
}

我也试过 blob.getAs('image/jpeg'),但那只是 returns 一个包含文本 Blob.

的 4 字节文件

有什么想法吗?我尝试了几种不同的字符集,Windows-1252 似乎给出了最接近的结果。

这个示例脚本怎么样?当你使用它时,请定义date。在我的测试中,我还可以确认 base64 编码的 jpeg 文件可以在 https://www.base64decode.org/.

处解码

以及更新doPost()时,请注意如下。请将您的脚本作为新版本重新部署到 Web 应用程序。如果不执行此操作,则不会更新部署的 Web 应用程序的脚本。

示例脚本:

function doPost(e) {
  var decoded = Utilities.base64Decode(e.parameters.contents, Utilities.Charset.UTF_8);
  var blob = Utilities.newBlob(decoded, "image/jpeg", 'img_'+date+'.jpg'); // Please define date.
  DriveApp.createFile(blob);
}

卷曲示例:

如果您想使用 curl 尝试 doPost(),可以使用以下命令。使用时请输入base64编码的文件名和Web Apps URL.

curl -L -F "contents=`cat ### Filename ###`" "https://script.google.com/macros/s/#####/exec"

如果我误解了你的问题,我很抱歉。