如何重建一个blob图像从二进制字符串(客户端隐藏的表单字段)在谷歌应用程序脚本

How to reconstruct a blob for an image from a binary string (client side hidden form field) in Google Apps Script

本文关键字:表单 隐藏 客户端 字段 应用程序 谷歌 字符串 脚本 重建 何重建 一个      更新时间:2023-09-26

我试图使用谷歌HTMLService从客户端处理表单。棘手的部分是我想在表单中捕获粘贴的图像(来自剪贴板),将其发送到服务器端并将其保存在DriveApp中。

在客户端,我认为我能够根据这个页面捕获粘贴的图像:http://joelb.me/blog/2011/code-snippet-accessing-clipboard-images-with-javascript/

我的客户端代码看起来像这样:

function pasteHandler(e) {
   // We need to check if event.clipboardData is supported (Chrome)
   if (e.clipboardData) {
      // Get the items from the clipboard
      var items = e.clipboardData.items;
      if (items) {
         // Loop through all items, looking for any kind of image
         for (var i = 0; i < items.length; i++) {
            if (items[i].type.indexOf("image") !== -1) {
               // We need to represent the image as a file,
               var blob = items[i].getAsFile();
               // and use a URL or webkitURL (whichever is available to the browser)
               // to create a temporary URL to the object
               var URLObj = window.URL || window.webkitURL;
               var source = URLObj.createObjectURL(blob);
               var reader = new FileReader();
               reader.onload = function(e) {
                 document.getElementById("summaryImage").value= reader.result;
               }
               reader.readAsBinaryString(blob);
               // The URL can then be used as the source of an image
               createImage(source);
            }
         }
      }
   // If we can't handle clipboard data directly (Firefox), 
   // we need to read what was pasted from the contenteditable element
   } 
}

因此,更改只是使用FileReader读取blob并将其保存到表单中的隐藏字段中。

<input type="hidden" name="summaryImage" id='summaryImage' value=''>

我认为这部分工作得很好,因为我可以在客户端显示图像,并且隐藏字段也填充了字节流。

我不确定的是如何拾取隐藏字段的值,现在是一个"二进制字符串",并将其保存为一个适当的PNG文件在谷歌驱动器和/或查看它。

在服务器端,我能够保存任何上传的文件(使用输入文件表单元素),但请注意隐藏字段传递的二进制字符串。

我已经尝试了下面的东西:

blob = form.summaryImage;
DriveApp.createFile('TRIFILE2.png', blob, 'image/png');

这将创建一个文件,但不能被视为png。如果我在Google Drive中打开它,它显示如下。我想它知道这是一个PNG文件,但什么是正确的方式来转换它?

‰PNG

IHDR   y   2     Þ  R    IDATx í]mLTYš~Øl€I ÃF  ´šX ‰|Dc H(œ    TÿàcÒÅPkuÂGÿ°è B'*ì: èHÖ    =ÂàØà¸É”ýc¨ùa &–M75i„ ]0ÓR&’¢W£`RZ› ÅA·
LÒ`²¹›s?ªî­ïÂ[x©{ªÛÔ­óñž÷}žûž{îåT=i×JJ ÐWJ# Æ' %9¥) þ!Åã£á ’¬Š“€f²
h¦$S’U€€
B¤™LIV  * ‘f2%Y  ¨ DšÉ”d   ‚ i&S’U€€
B¤™LIV  * ‘f2%Y  ¨ DšÉ”d   ‚ i&S’U€€
B¤™LIV  * ‘f2%Y  ¨ DšÉ”d   ‚ i&S’U€€
B¤™LIV  * ‘f2%Y  ¨ DšÉ”d   ‚ i&S’U€€
B¤™LIV  * 1 a ú;^)N4 ®Sœ`  %™’¬  T "ÍdJ²
 PAˆ4“)É*@@ !ÒL¦$«   „H3™’¬  T "ÍdJ²
 PAˆ4“)É*@@ !ÒL¦$«   „H3™’¬  T "ÍdJ²
 PAˆ4“)É*@@ !ÒL¦$‹ pc -

我还尝试了Utilities.newBlob()函数,但无法弄清楚如何从二进制字符串中生成正确的Blob。

不要使用readAsBinaryString,而是使用readAsDataURL,它获得base64,并且您将不会有混乱的字符。

如果你需要服务器端代码,你可以按照我的代码和Sandy Good教程:

使用Google App Script上传多个文件到Google Drive