How do I convert jpg or png image to Blob via a Google Apps Script Web App?

后端 未结 1 1114
春和景丽
春和景丽 2020-12-11 12:58

I want to http post an image from html form to google apps script web app, and then add that image to google drive.

my apps script is below.

function d         


        
相关标签:
1条回答
  • 2020-12-11 13:25

    How about following sample? Added "getAs()". https://developers.google.com/apps-script/reference/drive/file#getAs(String)

    These are very simple html and gas script I used for this test.

    HTML: This file name is "form.html".

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

    GAS script:

    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);  
    }
    

    For this sample script, if you want to save as a jpeg file, please change 'contentType' from 'image/png' to 'image/jpeg'. When you upload png file for contentType of 'image/jpeg', the png file is converted to jpeg file by 'getAs()'.

    Updated: March 19, 2020

    When V8 is enabled, it seems that this.parentNode cannot be sent to Google Apps Script side. I'm not sure whether this is a bug or the specification. I think that this might be resolved in the future update. But as the current workaround, I would like to add one more sample script for uploading the file using Web Apps, dialog and sidebar.

    In this case, the file is sent to Google Apps Script side as the byte array. And the file is created from the byte array at Google Apps Script side.

    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>
    

    Google Apps Script: 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.";
    }
    
    0 讨论(0)
提交回复
热议问题