簡體   English   中英

如何從Google Apps腳本中的二進制字符串(客戶端隱藏的表單字段)重構圖像的Blob

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

我正在嘗試使用Google 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=''>

我認為這部分工作正常,因為我可以在客戶端顯示圖像,並且隱藏字段也填充有字節流。

我不確定的是如何獲取隱藏字段的值(現在是“二進制字符串”)並將其另存為Google Drive中的適當PNG文件和/或查看它。

在服務器端,我能夠保存任何上載的文件(使用輸入文件表單元素),但請注意隱藏字段傳遞的二進制字符串。

我已經嘗試過以下方法:

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

這確實會創建一個文件,但不能將其視為png。 如果我在Google雲端硬盤中打開它,則顯示如下。 我想它知道這是一個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腳本將多個文件上傳到Google雲端硬盤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM