【问题标题】:Calling Image File on Google App Scripts to Upload into GoogleDrive在 Google App 脚本上调用图像文件以上传到 Google Drive
【发布时间】:2020-06-23 16:45:23
【问题描述】:

我正在尝试设置一种将图像文件上传到谷歌驱动器的方法。它将使用 timeid 创建一个文件夹,并将图像放在它创建的文件夹中。我无法调出图像文件。这就是我尝试的方式,创建了文件夹但没有图像。

请忽略 timeid 变量的任何缺失 var。这工作正常。

给出的错误: ReferenceError: imgInp 未定义

提前感谢您的帮助!

代码.gs

  var day = d.getDate();
  var month = d.getUTCMonth();
  var hour = d.getHours();
  var minutes = d.getMinutes();
  var realmonth = month+1;
  var timeid = String(year)+"-"+String(realmonth)+"-"+String(day)+"-"+String(hour)+"-"+String(minutes);
  var foldername=timeid;
  var parentFolder=DriveApp.getFolderById("##############");

function upload(){
  var newFolder=parentFolder.createFolder(timeid);

  var folderidlookup = newFolder.getId();

  var destination = DriveApp.getFolderById(folderidlookup);
  var imgf = imgInp;
  var contentType = 'image/jpeg';
  var imgf = imgf.getAs(contentType);
  destination.createFile(imgf)


}

HTML

       <form>

        <div class="file-field input-field">

         <div class="waves-effect waves-light btn" id="wholebtn"><i class="material-icons right">cloud</i>Browse
         <input type="file" name="imgInp" id="imgInp" onchange="loadFile(event)">

        </div> 
        <div class="file-path-wrapper">
         <input type="text" class="file-path">
        </div>
        </div>
       </form>
    <button class="btn waves-effect waves-light" type="submit" name="action" id ="button">Submit
      <i class="material-icons right">send</i>
    </button>

JS

<script>
  document.getElementById("button").addEventListener("click",upload); 

  function upload(){

     google.script.run.upload();

  }
</script>

【问题讨论】:

标签: javascript html google-apps-script


【解决方案1】:

文件上传对话框

从脚本编辑器运行upLoadMyDialog() 以启动它。选择文件并点击上传。

function fileUpload(obj) {
  var d=new Date();
  var ts=Utilities.formatDate(d, Session.getScriptTimeZone(), "yyyy-MM-dd-HH-mm");
  var folder=DriveApp.getFolderById("****** Enter FolderId *******");
  var file=folder.createFile(obj.file1).setName(ts);
}

function uploadMyDialog() {
  var ss=SpreadsheetApp.getActive();
  var html='<form><input type="file" name="file1"/><br /><input type="button" value="Upload" onClick="google.script.run.fileUpload(this.parentNode);" /></form>';  
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html),"Upload File");
}

使用事件监听器:

function uploadMyDialog() {
  var ss=SpreadsheetApp.getActive();
  var html='<form id="f1"><input type="file" name="file1"/><br /><input type="button" value="Upload" id="btn1" /></form>'; 
  html+='<script>window.onload=function(){document.getElementById("btn1").addEventListener("click",function(){google.script.run.fileUpload(document.getElementById("f1"))})}</script>';
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html),"Upload File");
}

【讨论】:

  • 有没有办法用 .addeventlistener 做到这一点?我正在尝试使用此事件侦听器在单击同一按钮后在同一个按钮上运行两个功能。谢谢!
【解决方案2】:

你得到的错误是因为你试图使用一个imgInp 变量,你没有在代码的任何部分定义它。您可以从输入中获取 blob 文件,将其转换为二进制数组字符串,将其传递到服务器端,最后使用它来创建您的 blob 和给定的驱动器文件,为此我使用了来自 answer 的代码.

使用来自HTML Service guide 的有关如何使用表单以及成功和失败处理程序的示例,我将以下代码放在一起,成功上传了给定的图像:

Index.html

<!DOCTYPE html>
<html>
<head>
    <base target="_top">
</head>
<body>
    <form>
        <div class="file-field input-field">
            <div class="waves-effect waves-light btn" id="wholebtn"><i class="material-icons right">cloud</i>Browse
                <input type="file" name="imgInp" id="imgInp">
            </div>
            <div class="file-path-wrapper">
                <input type="text" class="file-path">
            </div>
        </div>
        <button class="btn waves-effect waves-light" name="action" id="button">Submit
            <i class="material-icons right">send</i>
        </button>
    </form>
    <script>
        // Prevent forms from submitting.
        function preventFormSubmit() {
            var forms = document.querySelectorAll('form');
            for (var i = 0; i < forms.length; i++) {
                forms[i].addEventListener('submit', function(event) {
                    event.preventDefault();
                });
            }
        }

        // Add event listeners 
        window.addEventListener('load', preventFormSubmit);
        document.getElementById("button").addEventListener("click", upload);

        // Handler function
        function logger(e) {
            console.log(e)
        }

        async function upload() {
            // Get all the file data
            let file = document.querySelector('input[type=file]').files[0];

            // Get binary content, we have to wait because it returns a promise 
            let fileBuffer = await file.arrayBuffer();
            // Get the file content as binary and then convert it to string 
            const data = (new Uint8Array(fileBuffer)).toString();
            // Pass the binary array string to uploadG funciton on code.gs
            google.script.run.withFailureHandler(logger).withSuccessHandler(logger).uploadG(data);
        }
    </script>
</body>
</html>

代码.gs

function doGet() {
  return HtmlService.createHtmlOutputFromFile('Index');
}

function uploadG(imgInp){
  var parentFolder=DriveApp.getFolderById("[FOLER-ID]");
  var newFolder = parentFolder.createFolder('test webApp');
  var folderidlookup = newFolder.getId();

  var destination = DriveApp.getFolderById(folderidlookup);
  var contentType = 'image/jpeg';
  // Convert the binary array string to array and use it to create the Blob
  var blob = Utilities.newBlob(JSON.parse("[" + imgInp + "]"), contentType);
  blob = blob.getAs(contentType);
  destination.createFile(blob)

  return 'Filed uploaded!';
}

【讨论】:

  • 谢谢!你真的帮助了我。但是,一旦进入驱动器,文件名就会不断更改为 null。我怎样才能保留文件名?
  • 我尝试使用 createFile 参数从一个变量中给它一个名称,该变量是日期(我正在做:destination.createFile(timeid,blob) 但这给了文件名称但是它不再是图像了。有什么建议吗?谢谢!
  • 没关系,我用 .newblob 给它起了个名字!感谢您的帮助!
猜你喜欢
  • 2019-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 2012-08-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多