【问题标题】:save an image to document properties in Google App Script将图像保存到 Google App Script 中的文档属性
【发布时间】:2021-06-03 11:17:23
【问题描述】:

目前,我正在从 HTML 表单中上传图像文件,并使用以下代码将其转换为 base64:

fileImput.addEventListener("change", function() {
  if (file = this.files[0]) {    
let reader = new FileReader();
    reader.readAsDataURL(file);
     reader.onload = function() {
     var base64String = reader.result;
    }
}

我将 base64String 传递给服务器并将其保存在文档的属性中。

到那里为止,一切都很完美。问题是我需要将该图像文件包含在电子邮件中,使用 blob 格式包含图像,并在 HTML 表单中包含使用 base64 格式的图像。为了更复杂,我从 Drive 中获取了一些图像文件并获取文件的 blob:

driveFile.getBlob();

我找不到任何方法在应用脚本中将 base64 转换为 blob,反之亦然。

另外,我希望完全了解 blob 格式。如果您可以参考我一些好的文档,我将非常感激。

【问题讨论】:

    标签: google-apps-script base64 blob


    【解决方案1】:

    我相信你的目标如下。

    • 您希望将 driveFile.getBlob() 的 Blob 转换为 base64 数据。
    • 您希望将 base64 数据转换为 driveFile.getBlob() 的 Blob。
    • 您正在使用 Google Apps 脚本。

    1。从 Blob 转换为 base64。

    const blob = DriveApp.getFileById("### fileId ###").getBlob();
    const base64 = Utilities.base64Encode(blob.getBytes());
    
    • 可以使用Utilities.base64Encode()从字节数组转换Base64数据。
    • 在这种情况下,base64 数据没有标头。因此,当您想将此数据用作数据 URL 时,请添加 data:[<mediatype>][;base64],<data> 之类的标头。 Ref

    2。从 base64 转换为 Blob。

    const base64 = "###";
    const blob = Utilities.newBlob(Utilities.base64Decode(base64), "### mimeType ###", "### filename ###");
    
    • 使用Utilities.base64Decode()转换base64数据时,返回字节数组。为了将其转换为 blob,使用了Utilities.newBlob()。在这种情况下,可以包含 mimeType 和文件名。

    参考资料:

    【讨论】:

    • 好的。我是一个傻瓜。我很接近,但是......出于一些愚蠢的原因,我使用的是 Utilities.base64EncodeWebSafe () 方法,我猜它返回的东西不同。除了说谢谢,我无话可说,非常感谢@Tanaike
    • @Ppica88 感谢您的回复。我很高兴你的问题得到了解决。也谢谢你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    相关资源
    最近更新 更多