猿问

调用Google应用程序脚本上的图像文件上传到GoogleDrive

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


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


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


预先感谢您的帮助!


Code.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)



}


网页


       <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>


慕田峪7331174
浏览 101回答 2
2回答

狐的传说

您收到的错误是因为您尝试使用一个imgInp在代码的任何部分都没有定义的变量。您可以从输入中获取 blob 文件,将其转换为二进制数组字符串,将其传递到服务器端,最后使用它来创建您的 blob 和给定的 Drive 文件。使用HTML 服务指南中有关如何使用表单以及成功和失败处理程序的示例,我整理了以下代码,该代码可以成功上传给定图像:索引.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>Code.gsfunction 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!';}

牧羊人nacy

文件上传对话框从脚本编辑器运行upLoadMyDialog()以开始使用。选择文件并单击上传。function fileUpload(obj) {&nbsp; var d=new Date();&nbsp; var ts=Utilities.formatDate(d, Session.getScriptTimeZone(), "yyyy-MM-dd-HH-mm");&nbsp; var folder=DriveApp.getFolderById("****** Enter FolderId *******");&nbsp; var file=folder.createFile(obj.file1).setName(ts);}function uploadMyDialog() {&nbsp; var ss=SpreadsheetApp.getActive();&nbsp; var html='<form><input type="file" name="file1"/><br /><input type="button" value="Upload" onClick="google.script.run.fileUpload(this.parentNode);" /></form>';&nbsp;&nbsp;&nbsp; SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html),"Upload File");}使用事件监听器:function uploadMyDialog() {&nbsp; var ss=SpreadsheetApp.getActive();&nbsp; var html='<form id="f1"><input type="file" name="file1"/><br /><input type="button" value="Upload" id="btn1" /></form>';&nbsp;&nbsp; html+='<script>window.onload=function(){document.getElementById("btn1").addEventListener("click",function(){google.script.run.fileUpload(document.getElementById("f1"))})}</script>';&nbsp; SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html),"Upload File");}
随时随地看视频慕课网APP

相关分类

Html5
我要回答