Google Apps脚本可用作Web应用但不是电子表格脚本

时间:2016-03-29 15:16:02

标签: javascript google-apps-script

我有一个部署为Web App的独立脚本。我的代码完全像Web应用程序一样工作。但是,我的目标是在电子表格项目中使用该代码。

我将代码复制并粘贴到电子表格脚本中并进行了一些更改,使其在弹出式模态对话框窗口中工作,但它不像部署的Web应用程序那样工作。代码似乎没有向Code.gs返回任何数据。在代码路径上的各个点运行警报后,我发现了故障点,但我不确定如何解决它。

来自正在运行的WebApp的代码(2个文件:Code.gs& form.html):

## Code.gs file ##
function doGet() {
  return HtmlService.createHtmlOutputFromFile('form')
    .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

function uploadFileToDrive(base64Data, fileName, totalFiles, finalCount) {
  try{
    var splitBase = base64Data.split(','),
        type = splitBase[0].split(';')[0].replace('data:','');

    var byteCharacters = Utilities.base64Decode(splitBase[1]);
    var ss = Utilities.newBlob(byteCharacters, type);
    ss.setName(fileName);

    var dropbox = "stuff"; // Folder Name
    var folder, folders = DriveApp.getFoldersByName(dropbox); // Get folders by name

    if (folders.hasNext()) {
      folder = folders.next();
    } else {
      folder = DriveApp.createFolder(dropbox);
    }
    var file  = folder.createFile(ss);

    // BEGIN LOGGING FILE NAMES AND IDs
    var dropboxId = "SOME_FOLDER_ID_HERE" // Folder ID
    var theFolder = DriveApp.getFolderById(dropboxId); // Get folder by ID
    var list     = [];
    var theBlobs = [];
    if (totalFiles == finalCount) {
      var files = theFolder.getFiles();
      while (files.hasNext()) {
        var theFile = files.next();
        list.push(theFile.getId());
      }
      for (var i = 0; i < list.length; i++) {
        Logger.log(DriveApp.getFileById(list[i]).getName() + " : " + list[i]);
        theBlobs.push(DriveApp.getFileById(list[i]).getBlob());
      }
      Logger.log(theBlobs);
      // END LOGGING FILE NAMES AND IDs


      // BEGIN ZIPPING UP FILES
        var newZip = theFolder.createFile(Utilities.zip(theBlobs, 'zippedFiles.zip'));
        var zipId  = newZip.getId();
        Logger.log("Zip Id: " + zipId);
      // END ZIPPING UP FILES


      // BEGIN TRASHING UPLOADED FILES
      for (var i = 0; i < list.length; i++) {
        DriveApp.getFileById(list[i]).setTrashed(true);
      }
      // END TRASHING UPLOADED FILES
    }

    return file.getName();
  }catch(e){
    return 'Error: ' + e.toString();
  }
}


## form.html ##
<body>
  <div id="formcontainer">

    <form id="myForm">

      <label for="myFile">Upload File(s):</label><br />

      <input type="file" name="filename" id="myFile" multiple />

      <input type="button" class="blue" value="Submit" onclick="iteratorFileUpload()" /><br /><br />

    </form>
  </div>

  <div id="output"></div>

  <div id="progressbar">
    <div class="progress-label"></div>
  </div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="https://googledrive.com/host/0By0COpjNTZPnZTBvVGZOSFRhREE/add-ons.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

<script>
var numUploads   = {};
numUploads.done  = 0 ;
numUploads.total = 0 ;

// Upload the files into a folder in drive...set to send them all to one folder (specificed in the .gs file)
function iteratorFileUpload() {
    var allFiles = document.getElementById('myFile').files;

    if (allFiles.length == 0) {
        alert('No file selected!');
    } else { // Show Progress Bar
        var myCount = 0; // Begin count to compare loops through
        numUploads.total = allFiles.length;
        $('#progressbar').progressbar({
        value : false
        });
        $(".progress-label").html('Preparing files..');
        // Send a file at a time
        for (var i = 0; i < allFiles.length; i++) {
            myCount++; // Increment count each time before sending the file to drive
            sendFileToDrive(allFiles[i], allFiles.length, myCount);
        }
    }
}

function sendFileToDrive(file, totalFiles, newCount) {
    var reader = new FileReader();
    reader.onload = function (e) {
        var content = reader.result;
        google.script.run.withSuccessHandler(updateProgressbar).uploadFileToDrive(content, file.name, totalFiles, newCount);
    }
    reader.readAsDataURL(file);
}

function updateProgressbar( idUpdate ){
   numUploads.done++;
   var porc = Math.ceil((numUploads.done / numUploads.total)*100);
   $("#progressbar").progressbar({value: porc });
   $(".progress-label").text(numUploads.done +'/'+ numUploads.total);
   if( numUploads.done == numUploads.total ){
      numUploads.done = 0;
   };
}

function fileUploaded(status) {
  document.getElementById('myForm').style.display = 'none';
  document.getElementById('output').innerHTML = status;
}
</script>

  <style>
    body {
      max-width: 400px;
      padding: 20px;
      margin: auto;
    }
    input {
      display: inline-block;
      width: 100%;
      padding: 5px 0px 5px 5px;
      margin-bottom: 10px;
      -webkit-box-sizing: border-box;
      ‌​ -moz-box-sizing: border-box;
      box-sizing: border-box;
    }
    select {
      margin: 5px 0px 15px 0px;
    }
    input[type="submit"] {
      width: auto !important;
      display: block !important;
    }
    input[type="file"] {
      padding: 5px 0px 15px 0px !important;
    }
#progressbar{
    width: 100%;
    text-align: center;
    overflow: hidden;
    position: relative;
    vertical-align: middle;

}
.progress-label {
      float: left;
margin-top: 5px;
      font-weight: bold;
      text-shadow: 1px 1px 0 #fff;
          width: 100%;
    height: 100%;
    position: absolute;
    vertical-align: middle;
    }
  </style>
</body>

当部署为电子表格容器绑定应用程序时,代码如下(2个文件:Code.gs&amp; form.html):

## Code.gs ##
function uploadFiles() {

  function doGet() {
    return SpreadsheetApp.getUi().showModalDialog(HtmlService.createHtmlOutputFromFile('form').setSandboxMode(HtmlService.SandboxMode.IFRAME), "Upload Files");
  }

  doGet();

  function uploadFileToDrive(base64Data, fileName, totalFiles, finalCount) {
    try{
      var splitBase = base64Data.split(','),
          type = splitBase[0].split(';')[0].replace('data:','');

      var byteCharacters = Utilities.base64Decode(splitBase[1]);
      var ss = Utilities.newBlob(byteCharacters, type);
      ss.setName(fileName);

      var dropbox = "stuff"; // Folder Name
      var folder, folders = DriveApp.getFoldersByName(dropbox); // Get folders by name

      if (folders.hasNext()) {
        folder = folders.next();
      } else {
        folder = DriveApp.createFolder(dropbox);
      }
      var file  = folder.createFile(ss);

      // BEGIN LOGGING FILE NAMES AND IDs
      var dropboxId = "SOME_FOLDER_ID_HERE" // Folder ID
      var theFolder = DriveApp.getFolderById(dropboxId); // Get folder by ID
      var list     = [];
      var theBlobs = [];
      if (totalFiles == finalCount) {
        var files = theFolder.getFiles();
        while (files.hasNext()) {
          var theFile = files.next();
          list.push(theFile.getId());
        }
        for (var i = 0; i < list.length; i++) {
          Logger.log(DriveApp.getFileById(list[i]).getName() + " : " + list[i]);
          theBlobs.push(DriveApp.getFileById(list[i]).getBlob());
        }
        Logger.log(theBlobs);
        // END LOGGING FILE NAMES AND IDs


        // BEGIN ZIPPING UP FILES
          var newZip = theFolder.createFile(Utilities.zip(theBlobs, 'zippedFiles.zip'));
          var zipId  = newZip.getId();
          Logger.log("Zip Id: " + zipId);
        // END ZIPPING UP FILES


        // BEGIN TRASHING UPLOADED FILES
        for (var i = 0; i < list.length; i++) {
          DriveApp.getFileById(list[i]).setTrashed(true);
        }
        // END TRASHING UPLOADED FILES
      }

      return file.getName();
    }catch(e){
      return 'Error: ' + e.toString();
    }
  }
}


## form.html ##
<body>
  <div id="formcontainer">

    <form id="myForm">

      <label for="myFile">Upload File(s):</label><br />

      <input type="file" name="filename" id="myFile" multiple />

      <input type="button" class="blue" value="Submit" onclick="iteratorFileUpload()" /><br /><br />

    </form>
  </div>

  <div id="output"></div>

  <div id="progressbar">
    <div class="progress-label"></div>
  </div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="https://googledrive.com/host/0By0COpjNTZPnZTBvVGZOSFRhREE/add-ons.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

<script>
var numUploads   = {};
numUploads.done  = 0 ;
numUploads.total = 0 ;

// Upload the files into a folder in drive...set to send them all to one folder (specificed in the .gs file)
function iteratorFileUpload() {
    var allFiles = document.getElementById('myFile').files;

    if (allFiles.length == 0) {
        alert('No file selected!');
    } else { // Show Progress Bar
        var myCount = 0; // Begin count to compare loops through
        numUploads.total = allFiles.length;
        $('#progressbar').progressbar({
        value : false
        });
        $(".progress-label").html('Preparing files..');
        // Send a file at a time
        for (var i = 0; i < allFiles.length; i++) {
            myCount++; // Increment count each time before sending the file to drive
            sendFileToDrive(allFiles[i], allFiles.length, myCount);
        }
    }
}

function sendFileToDrive(file, totalFiles, newCount) {
    var reader = new FileReader();
    reader.onload = function (e) {
        var content = reader.result;
        google.script.run.withSuccessHandler(updateProgressbar).uploadFileToDrive(content, file.name, totalFiles, newCount);
    }
    reader.readAsDataURL(file);
}

function updateProgressbar( idUpdate ){
   numUploads.done++;
   var porc = Math.ceil((numUploads.done / numUploads.total)*100);
   $("#progressbar").progressbar({value: porc });
   $(".progress-label").text(numUploads.done +'/'+ numUploads.total);
   if( numUploads.done == numUploads.total ){
      numUploads.done = 0;
   };
}

/*
function updateProgressbar( idUpdate ){
   numUploads.done++;
   var porc = Math.ceil((numUploads.done / numUploads.total)*100);
   $("#progressbar").progressbar({value: porc });
   $(".progress-label").text(numUploads.done +'/'+ numUploads.total);
   if( numUploads.done == numUploads.total ){
      numUploads.done = 0;
   };
}
*/

function fileUploaded(status) {
  document.getElementById('myForm').style.display = 'none';
  document.getElementById('output').innerHTML = status;
}
</script>

  <style>
    body {
      max-width: 400px;
      padding: 20px;
      margin: auto;
    }
    input {
      display: inline-block;
      width: 100%;
      padding: 5px 0px 5px 5px;
      margin-bottom: 10px;
      -webkit-box-sizing: border-box;
      ‌​ -moz-box-sizing: border-box;
      box-sizing: border-box;
    }
    select {
      margin: 5px 0px 15px 0px;
    }
    input[type="submit"] {
      width: auto !important;
      display: block !important;
    }
    input[type="file"] {
      padding: 5px 0px 15px 0px !important;
    }
#progressbar{
    width: 100%;
    text-align: center;
    overflow: hidden;
    position: relative;
    vertical-align: middle;

}
.progress-label {
      float: left;
margin-top: 5px;
      font-weight: bold;
      text-shadow: 1px 1px 0 #fff;
          width: 100%;
    height: 100%;
    position: absolute;
    vertical-align: middle;
    }
  </style>
</body>

此时非工作代码停止: google.script.run.withSuccessHandler(updateProgressbar).uploadFileToDrive(content, file.name, totalFiles, newCount);

到目前为止,一切都很顺利,信息从一个函数传递到另一个函数。

在电子表格脚本中,文件永远不会上传到云端硬盘,并且html页面上显示的文件的计数器永远不会增加...它只会停止。

我所遇到的可能有助于解决这个问题的最接近的文章是:how to use google.script.run as if it was a function最初被提议作为此问题的解决方案Google Apps Script HTML Service: Passing variablesReturning a value using Date picker in HTMLService / Google Apps Script

提前感谢您的帮助!!

1 个答案:

答案 0 :(得分:0)

解决方案非常简单,因为底层代码已经作为独立的Web应用程序运行。

所需的唯一更改是Code.gs文件。

拉出代码的开头并将其保存在自己的顶层函数中:

function uploadFiles() {

  function doGet() {
    return SpreadsheetApp.getUi().showModalDialog(HtmlService.createHtmlOutputFromFile('form').setSandboxMode(HtmlService.SandboxMode.IFRAME), "Upload Files");
  }

  doGet();
}

然后将余数放在它自己的顶级函数中:

function uploadFileToDrive(base64Data, fileName, totalFiles, finalCount) {
  try{
    var splitBase = base64Data.split(','),
    type = splitBase[0].split(';')[0].replace('data:','');

    var byteCharacters = Utilities.base64Decode(splitBase[1]);
    var ss = Utilities.newBlob(byteCharacters, type);
    ss.setName(fileName);

    var dropbox = "stuff"; // Folder Name
    var folder, folders = DriveApp.getFoldersByName(dropbox); // Get folders by name

    if (folders.hasNext()) {
      folder = folders.next();
    } else {
      folder = DriveApp.createFolder(dropbox);
    }
    var file  = folder.createFile(ss);

    // BEGIN LOGGING FILE NAMES AND IDs
    var dropboxId = "SOME_FOLDER_ID_HERE" // Folder ID
    var theFolder = DriveApp.getFolderById(dropboxId); // Get folder by ID
    var list     = [];
    var theBlobs = [];
    if (totalFiles == finalCount) {
      var files = theFolder.getFiles();
      while (files.hasNext()) {
        var theFile = files.next();
        list.push(theFile.getId());
      }
      for (var i = 0; i < list.length; i++) {
        Logger.log(DriveApp.getFileById(list[i]).getName() + " : " + list[i]);
        theBlobs.push(DriveApp.getFileById(list[i]).getBlob());
      }
      Logger.log(theBlobs);
      // END LOGGING FILE NAMES AND IDs


      // BEGIN ZIPPING UP FILES
        var newZip = theFolder.createFile(Utilities.zip(theBlobs, 'zippedFiles.zip'));
        var zipId  = newZip.getId();
        Logger.log("Zip Id: " + zipId);
      // END ZIPPING UP FILES


      // BEGIN TRASHING UPLOADED FILES
      for (var i = 0; i < list.length; i++) {
        DriveApp.getFileById(list[i]).setTrashed(true);
      }
      // END TRASHING UPLOADED FILES
    }

    return file.getName();
  }catch(e){
    return 'Error: ' + e.toString();
  }
}

它现在可以完美地作为附加到电子表格的脚本!