如何使用 Google Apps 脚本 WebApp 和 JQuery 将 chrome 图像从 chrome 扩展到 Google 驱动器

How to POST images from chrome extension to Google Drive using Google Apps Script WebApp and JQuery

我有一个 Google Chrome 扩展,当我按下 CTRL + V 时,我需要它来生成 image/png 类型的图像(这工作正常)。之后,我需要使用 Google Apps Script 网络应用程序将此图像发送到 Google 驱动器。但我一直无法弄清楚如何做到这一点。我正在使用 ajax 和 jQuery

这是我用来捕捉和创建图像的代码,效果很好

$(partial).on('paste', e => { // partial is an dynamic html
    e = e.originalEvent
    let item = Array.from(e.clipboardData.items).find(x => /^image\//.test(x.type))
    let blob = item.getAsFile()
    let base = URL.createObjectURL(blob)
    let img = new Image()
    img.src = base
    img.onload = function () {
        let w = this.width
        let h = this.height
        $(partial).find('.img-evi').attr('width', w)
        $(partial).find('.img-evi').attr('height', h)
        $(partial).find('.img-evi').attr('src', base) // show the image paste in screen

        let reader = new FileReader() // try to send the image to Google Drive
        reader.onload = function (e) {
            const file = new File([blob], "capture.png", {
                type: 'image/png'
            })
            var fd = new FormData()
            fd.append("image", file)
            $.ajax({ // Call Google Apps Script WebApp by POST
                type: "POST",
                enctype: 'multipart/form-data',
                url: "https://script.google.com/macros/s/#########/exec",
                data: fd,
                processData: false,
                contentType: false,
                cache: false,
                success: (data) => {
                    alert("yes");
                },
                error: function (xhr, status, error) {
                    alert(xhr.responseText);
                }
            });
        }
        reader.readAsDataURL(blob);
    }
    img.remove()
})

在应用脚本中我有那个

function doPost(e) {
  let FOLDER = DriveApp.getFolderById('### Folder ID ######')
  let imgBlob = Utilities.newBlob(e.postData, 'image/png', "### how to get name ? ###")
  let fileId = FOLDER.createFile(imgBlob).getId()
  return ContentService.createTextOutput(JSON.stringify({
    ok: true,
    data: { id: fileId },
    title: 'Success',
    message: `The image id is ${fileId}.`
  })).setMimeType(ContentService.MimeType.JSON)
}

感谢您的帮助

修改点:

  • 在您的脚本中,file 是 Blob。我认为这不能直接用于发送到 Web 应用程序。
  • 在此修改中,数据被转换为 int8array,并将其作为字符串值发送到 Web Apps。
  • 为此,需要修改您的 Google Apps 脚本端。

当这些点反映到你的脚本中,就变成了下面这样。

Javascript 边:

发件人:

let reader = new FileReader() // try to send the image to Google Drive
reader.onload = function (e) {
    const file = new File([blob], "capture.png", {
        type: 'image/png'
    })
    var fd = new FormData()
    fd.append("image", file)
    $.ajax({ // Call Google Apps Script WebApp by POST
        type: "POST",
        enctype: 'multipart/form-data',
        url: "https://script.google.com/macros/s/#########/exec",
        data: fd,
        processData: false,
        contentType: false,
        cache: false,
        success: (data) => {
            alert("yes");
        },
        error: function (xhr, status, error) {
            alert(xhr.responseText);
        }
    });
}
reader.readAsDataURL(blob);

收件人:

let reader = new FileReader();
reader.onload = function (e) {
  const values = { data: [...new Int8Array(e.target.result)], filename: "capture.png", mimeType: "image/png" };
  $.ajax({
    url: "https://script.google.com/macros/s/###/exec",
    method: "POST",
    dataType: "json",
    data: JSON.stringify(values),
    processData: false,
    contentType: false,
    cache: false,
    success: (data) => {
      console.log(data)
      alert("yes");
    },
    error: function (xhr, status, error) {
      alert(xhr.responseText);
    }
  });
}
reader.readAsArrayBuffer(blob);

Google Apps 脚本端:

function doPost(e) {
  const { data, filename, mimeType } = JSON.parse(e.postData.contents);
  let FOLDER = DriveApp.getFolderById('### Folder ID ######');
  let imgBlob = Utilities.newBlob(data, mimeType, filename);
  let fileId = FOLDER.createFile(imgBlob).getId();
  return ContentService.createTextOutput(JSON.stringify({
    ok: true,
    data: { id: fileId },
    title: 'Success',
    message: `The image id is ${fileId}.`
  })).setMimeType(ContentService.MimeType.JSON)
}

注:

参考文献: