如何将文件上传添加到电子表格作为自定义菜单选项?

时间:2019-04-05 11:18:50

标签: google-apps-script google-sheets

我想制作一个电子表格CMS-从Firebase读取/写入数据,反之亦然。我到达了需要直接从电子表格而非任何其他页面上传文件的地步。

我添加了带有htmlService的自定义菜单,以输出模板,用户可以在其中单击并上传文件,并且该文件必须在Google脚本中进行处理,但是问题是我只得到了伪造的路径文件“ c:/fakepath/avatar.png”而不是Blob。

我在Google脚本中的文件:

upload.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
  </head>
  <body>
    <div>
        <div id="progress" ></div>


        <input type="file" name="upload" id="file">

        <input type="submit" value="Submit" class="action" onclick="form_data()" >
        <input type="button" value="Close" onclick="google.script.host.close()" />


    </div>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>
    <script>
      function form_data(){

        var values = [{
          "file":$("#upload").val(),

        }];

        google.script.run.withSuccessHandler(closeIt).upload(values);

      };

      function closeIt(){
        google.script.host.close()
      };

    </script>
  </body>
</html>

test.gs

function upload(values){
  //Display the values submitted from the dialog box in the Logger. 
  Logger.log(values); // here I'm getting file = c/fakepath/avatar.png while I 
       //need the file to send it as a post request or save it in google drive
};

我相信我应该使用FileReader,但是我尝试过并失败了:

      var file, 
        reader = new FileReader();

// Upload the file to Google Drive
  reader.onloadend = function(e) {
    google.script.run
      .upload(
         e.target.result, file.name
      );
  };
      function form_data(){
    reader.readAsDataURL(file);
}

custom menu file upload

1 个答案:

答案 0 :(得分:2)

  • 您要使用Google文档上的对话框将文件上传到Google云端硬盘。

如果我的理解是正确的,那么该修改如何?请认为这只是几个答案之一。

修改后的脚本:

Google Apps脚本:

function upload(obj) {
  var file = DriveApp.createFile(obj.upload);
  return {
    fileId: file.getId(),
    mimeType: file.getMimeType(),
    fileName: file.getName(),
  };
}

HTML:

请如下替换<body>...</body>。在此修改中,不使用jquery。

<body>
  <form> <!-- Modified -->
    <div id="progress" ></div>
    <input type="file" name="upload" id="file">
    <input type="button" value="Submit" class="action" onclick="form_data(this.parentNode)" >
    <input type="button" value="Close" onclick="google.script.host.close()" />
  </form>
  <script>
    function form_data(obj){ // Modified
      google.script.run.withSuccessHandler(closeIt).upload(obj);
    };
    function closeIt(e){ // Modified
      console.log(e);
      google.script.host.close();
    };
  </script>
</body>

注意:

  • 上载文件时,将返回创建的文件的文件ID,mimeType和文件名。您可以在控制台上看到它们。
  • 在这种方法中,因为使用了blob,所以最大文件大小为50 MB。请注意这一点。

如果我误解了您的问题,而这不是您想要的结果,我深表歉意。

相关问题