【问题标题】:How to link html back to the script - Uploading Script Google Drive如何将 html 链接回脚本 - 上传脚本 Google Drive
【发布时间】:2016-10-05 08:10:04
【问题描述】:

我最初在网上看到了这段代码,它允许用户通过一个页面将文件上传到他们的谷歌驱动器。该脚本会自动创建一个文件夹

//https://script.google.com/d/12EnDFZrsfpBubZ9lM7pnHIsn9M49_vyXm0TLBQ_pyx_ViAJH3HXgkoe9/edit?newcopy=true

所以您会注意到,最初这些代码应该部署为 web 应用程序,但我对其进行了调整以使其在侧边栏上运行。 html 部分加载正常,您实际上可以键入所有数据,但是一旦单击上传表单,它只会返回一个空白页面。我非常确信这是因为单击按钮没有再次连接到脚本,导致它失败

这是原始代码

/* The script is deployed as a web app and renders the form */
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html')
        .setSandboxMode(HtmlService.SandboxMode.NATIVE);
// This is important as file upload fail in IFRAME Sandbox mode.
}

/* This function will process the submitted form */
function uploadFiles(form) {

 try {

 // Name of the Drive folder where the files should be saved 
    var dropbox = "Database";
;
var folder, folders = DriveApp.getFoldersByName(dropbox);

// Find the folder, create if the folder does not exist 
if (folders.hasNext()) {
  folder = folders.next();
} else {
  folder = DriveApp.createFolder(dropbox);
}

// Get the file uploaded though the form as a blob 
var blob = form.myFile;    
var file = folder.createFile(blob);    

// Set the file description as the name of the uploader 
file.setName(form.myCode + " "  + form.myfilename + " - " + form.myID + " - " + form.myName); 
file.setDescription("Uploaded by " + form.myName + " - " + form.myEmail);

// Return the download URL of the file once its on Google Drive 
return "File uploaded successfully, please check your drive with this link for confirmation: " + file.getUrl();

 } catch (error) {

// If there's an error, show the error message 
return error.toString();
}

}

HTML 在这里

<!-- Include the Google CSS package -->
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
 
<!-- You can also include your own CSS styles -->
<style>
  form { margin: 40px 20px auto; }
  input { display:inline-block; margin: 20px; }
</style>
 
<script>
  
  // The function will be called after the form is submitted
  function uploadFile() {
    document.getElementById('uploadFile').value = "Uploading File..";
    google.script.run
       .withSuccessHandler(fileUploaded)
       .uploadFiles(document.getElementById("labnol"));
    return false;
  }
 
  // This function will be called after the Google Script has executed
  function fileUploaded(status) {
    document.getElementById('labnol').style.display = 'none';
    document.getElementById('output').innerHTML = status;
  }
  
</script>
 
<!-- This is the HTML form -->
<form id="labnol">
 
  <!-- Text input fields -->
  File Upload<br>
  <br>
  Your Name:<br>
  <input type="text" name="myName" placeholder="Your name.."> <br><br>
  Email Address: <br>
  <input type="email" name="myEmail" placeholder="Your email.."> <br><br>
  ID? <br>
  <input type="number" name="myID" placeholder="Your ID.."> <br><br>
  Upload Code: <br>
  <input type="text" name="myCode" placeholder="Your Upload code.."> <br><br>
  File Name: <br>
  <input type="text" name="myfilename" placeholder="Your File Name">  <br><br>
 
  <!-- File input filed -->
  <input type="file" name="myFile">
 
  <!-- The submit button. It calls the server side function uploadfiles() on click -->
  <br>
  <input type="submit" id="uploadFile" value="Upload File" 
         onclick="this.value='Uploading..';uploadFile();">
 
</form>
 
<!-- Here the results of the form submission will be displayed -->
<div id="output"></div>

所以我从原始代码中对其进行了调整以替换顶部

function showSidebar() {
var html = HtmlService.createHtmlOutputFromFile('form')
  .setTitle('Upload Form')
  .setWidth(250);
 SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
  .showSidebar(html);
}

// This function will process the submitted form 
function uploadFile(form) {

 try {

// Name of the Drive folder where the files should be saved 
    var dropbox = "Database";
 ;
  var folder, folders = DriveApp.getFoldersByName(dropbox);

  // Find the folder, create if the folder does not exist 
  if (folders.hasNext()) {
  folder = folders.next();
} else {
  folder = DriveApp.createFolder(dropbox);
}

// Get the file uploaded though the form as a blob 
var blob = form.myFile;    
var file = folder.createFile(blob);    

// Set the file description as the name of the uploader 
file.setName(form.myCode + " "  + form.myfilename + " - " + form.myID + " - " + form.myName); 
file.setDescription("Uploaded by " + form.myName + " - " + form.myEmail);

// Return the download URL of the file once its on Google Drive 
return "File uploaded successfully, please check your drive with this link for confirmation: " + file.getUrl();

 } catch (error) {

 // If there's an error, show the error message 
return error.toString();
 }

}

所以我基本上用脚本替换了顶部以加载侧边栏和html“表单”,但出现的错误是点击上传时,它不起作用。

我猜是这个部分

 <input type="submit" id="uploadFile" value="Upload File" 
     onclick="this.value='Uploading..';uploadFile();">

由于onClick,它应该运行函数uploadFile(),但它不起作用。 我一直试图解决这个问题很长一段时间,但似乎无法使最后一部分工作。所以我在这里问是否有人可以帮助我解决这个编码问题

【问题讨论】:

    标签: javascript google-apps-script google-sheets spreadsheet google-spreadsheet-api


    【解决方案1】:

    基于此文档:HTML 服务:与服务器功能通信

    google.script.run 是一个异步客户端 JavaScript API,它允许 HTML 服务页面调用服务器端应用程序脚本函数。以下示例展示了 google.script.run 的最基本功能——来自客户端 JavaScript 的 calling a function on the server

    检查 Form 如何与 Apps 脚本通信。如果您使用表单元素作为参数调用服务器函数,则表单将成为单个对象,其中字段名称作为键,字段值作为值。除了文件输入字段的内容变成Blob 对象外,所有值都转换为字符串。

    这里有示例代码:

    <!DOCTYPE html>
    <html>
      <head>
        <base target="_top">
        <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();
              });
            }
          }
          window.addEventListener('load', preventFormSubmit);
    
          function handleFormSubmit(formObject) {
            google.script.run.withSuccessHandler(updateUrl).processForm(formObject);
          }
          function updateUrl(url) {
            var div = document.getElementById('output');
            div.innerHTML = '<a href="' + url + '">Got it!</a>';
          }
        </script>
      </head>
      <body>
        <form id="myForm" onsubmit="handleFormSubmit(this)">
          <input name="myFile" type="file" />
          <input type="submit" value="Submit" />
        </form>
        <div id="output"></div>
     </body>
    </html>
    

    最好简化在OnSubmit 事件中调用函数的方式。此外,您可以使用 Execution Transcript 调试脚本,这是脚本运行时对 Google Apps 脚本服务的每次调用的记录。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2021-12-10
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      • 1970-01-01
      相关资源
      最近更新 更多