如何通过 Google Apps Script Web App 将 jpg 或 png 图像转换为 Blob?

Kat*_*307 1 blob web-applications google-apps-script

我想将 html 表单中的图像通过 http 发布到谷歌应用程序脚本网络应用程序,然后将该图像添加到谷歌驱动器。

我的应用程序脚本如下。

function doPost(e){
  var date = new Date();
  var timestamp = date.toString()
  var adress = e.parameter.adress;
  var cost = e.parameter.cost;
  var item = e.parameter.item;
  var check = e.parameter.image;

  //add file to drive
  var destination_id = "some ID"
  var destination = DriveApp.getFolderById(destination_id);
  destination.createFile(check);
};
Run Code Online (Sandbox Code Playgroud)

当我执行时,它返回一个错误; cannot find method: createFile(String)

我认为这是因为“检查”是一个字符串,我想将提交的图像转换为Blob。

我怎样才能做到这一点?

Tan*_*ike 5

下面的示例怎么样?添加了“getAs()”。https://developers.google.com/apps-script/reference/drive/file#getAs(String)

这些是我用于此测试的非常简单的 html 和 gas 脚本。

HTML:此文件名为“form.html”。

<form>
  <input type="file" name="imageFile">
  <input type="button" value="ok" onclick="google.script.run.upload(this.parentNode)">
</form>
Run Code Online (Sandbox Code Playgroud)

气体脚本:

function doGet() {
  return HtmlService.createHtmlOutputFromFile('form.html');
}

function upload(e) {
  var destination_id = "some ID";
  var img = e.imageFile;
  var contentType = "image/jpeg";
  var destination = DriveApp.getFolderById(destination_id);
  var img = img.getAs(contentType);
  destination.createFile(img);  
}
Run Code Online (Sandbox Code Playgroud)

对于此示例脚本,如果您想保存为 jpeg 文件,请将 'contentType' 从 'image/png' 更改为 'image/jpeg'。当您为“image/jpeg”的 contentType 上传 png 文件时,png 文件将通过“getAs()”转换为 jpeg 文件。

更新时间:2020 年 3 月 19 日

启用 V8 时,似乎this.parentNode无法发送到 Google Apps 脚本端。我不确定这是错误还是规范。我认为这可能会在未来的更新中得到解决。但作为当前的解决方法,我想再添加一个示例脚本,用于使用 Web 应用程序、对话框和侧边栏上传文件。

在这种情况下,文件将作为字节数组发送到 Google Apps 脚本端。该文件是从 Google Apps Script 端的字节数组创建的。

HTML 和 JavaScript: index.html

<input id="file" type="file" onchange="saveFile(this)" />
<script>
  function saveFile(f) {
    const file = f.files[0];
    const fr = new FileReader();
    fr.onload = function(e) {
      const obj = {
        filename: file.name,
        mimeType: file.type,
        bytes: [...new Int8Array(e.target.result)]
      };
      google.script.run.withSuccessHandler(e => console.log(e)).saveFile(obj);
    };
    fr.readAsArrayBuffer(file);
  }
</script>
Run Code Online (Sandbox Code Playgroud)

Google Apps 脚本: Code.gs

function doGet() {
  return HtmlService.createHtmlOutputFromFile('index.html');
}

function saveFile(e) {
  var blob = Utilities.newBlob(e.bytes, e.mimeType, e.filename);
  DriveApp.createFile(blob);
  return "Done.";
}
Run Code Online (Sandbox Code Playgroud)