Google脚本,使用用户输入下载文件

时间:2016-02-04 11:02:24

标签: google-apps-script google-drive-api

我编写了以下Google Apps脚本,该脚本记录文件名并生成文件的直接下载链接。到目前为止它完美运作。

function SearchFiles() {
  var searchFor ='title contains "Letter"';
  var names =[];
  var fileIds=[];
  var files = DriveApp.searchFiles(searchFor);
  while (files.hasNext()) {
    var file = files.next();
    var fileId = file.getId();// To get FileId of the file
    fileIds.push(fileId);
    var name = file.getName();
    names.push(name);
    
  }

  for (var i=0;i<names.length;i++){
    Logger.log(names[i]);
    Logger.log("https://drive.google.com/uc?export=download&id=" + fileIds[i]);
    
  }

}

日志是这样的:

[16-02-04 16:29:27:794 IST] Letter to SRL for Laboratory
[16-02-04 16:29:27:795 IST] https://drive.google.com/uc?export=download& id=1wTDiv7jensErQl2CODxkTb-tYAvv3vDYPGDECEPrXm
[16-02-04 16:29:27:796 IST] Letters_Nirvedanandaji_I.docx
[16-02-04 16:29:27:797 IST] https://drive.google.com/uc?export=download&id=0B_NmiOlCM-VTa3VrNjF0NE9iNWRQODNOME90VGF3WUV2OW5

现在的问题是:

  1. 我希望用户提供搜索字词(var searchFor)。
  2. 假设搜索字词为“1234.doc”,则应向用户显示生成的下载链接。我将确保搜索词返回唯一值。
  3. 任何人都应该能够使用该脚本(无需任何身份验证)

1 个答案:

答案 0 :(得分:2)

首先,您需要在脚本文件中使用doGet()函数,该函数通常位于:

代码

function doGet() {
  var template = HtmlService.createTemplateFromFile('Index');

  // Build and return HTML in IFRAME sandbox mode.
  return template.evaluate()
      .setTitle('RKMS Kankhal Lab Portal')
      .setSandboxMode(HtmlService.SandboxMode.IFRAME);
};

function SearchFiles(inputValueFromUser) {
  Logger.log('inputValueFromUser: ' + inputValueFromUser);

  if (inputValueFromUser==="") {return 'No Search String';};
  //inputValueFromUser = "";
  //inputValueFromUser = inputValueFromUser !== ""?inputValueFromUser:"Jan8Test";
  var searchFor ='title contains "' + inputValueFromUser + '"';
  Logger.log('searchFor: ' + searchFor);

  var file,
      fileId,
      name,
      downloadURL = "",
      arryOfUrls = [];

  var files = DriveApp.searchFiles(searchFor);

  Logger.log('files: ' + files);
  Logger.log(files.hasNext());

  while (files.hasNext()) {
    file = files.next();
    fileId = file.getId();// To get FileId of the file
    name = file.getName();

    Logger.log("https://drive.google.com/uc?export=download&id=" + fileId);

    downloadURL = "https://drive.google.com/uc?export=download&id=" + fileId;
    arryOfUrls.push(downloadURL);
  };

  Logger.log('arryOfUrls: ' + arryOfUrls);
  return arryOfUrls;//.toString(); //Send array of download urls back to client side JavaScript 
};

然后您需要主HTML表单,通常命名为:

索引

<!DOCTYPE html>
<html>

  <body>
    <h1>
    The Title of The Page Here
    </h1>
    <h2 id="main-heading">Online Lab reports</h2>
    <div class="block result-display" id="results">
      Enter your Lab_ID: <input id="idFileName" type="text" placeholder="Enter the file name">
      <div class="hidden" id="error-message">

      </div>
    </div>

    <div id='idMyMessage'>

    </div>

    <button onmouseup="getTheData()">Get Download Link</button>

    <!-- Use a templated HTML printing scriptlet to import JavaScript. -->
    <?!= HtmlService.createHtmlOutputFromFile('JS_MainPageCode').getContent(); ?>
  </body>
</html>

JS_MainPageCode:

<script>
  function updateDisplay(arrayOfUrls) {
    console.log('arrayOfUrls: ' + arrayOfUrls);

    if (arrayOfUrls === 'No Search String') {return;};

    var headingText = "Displaying arrayOfUrls for " + arrayOfUrls + " folder:";

    document.getElementById('main-heading').textContent = headingText;

    var dataLngth = arrayOfUrls.length;
    console.log('dataLngth: ' + dataLngth);

    for (var i = 0; i < dataLngth; i++) {
      var name = arrayOfUrls[i];
      document.getElementById('results').insertAdjacentHTML('beforeend', '<div>' + name + '</div>');
    }
  }

  window.getTheData = function() {
    var userInput = document.getElementById("idFileName").value;
    console.log('userInput: ' + userInput);

    document.getElementById('results')innerHTML = "";//Reset to blank in case there was an error message

    if (userInput === '') {
      document.getElementById('results').insertAdjacentHTML('beforeend', '<div>' + 'Please Enter a File Name' + '</div>');
      return;
    };

    google.script.run
      .withSuccessHandler(updateDisplay)
      .SearchFiles(userInput);
  };
</script>

如果要在单独的文件中使用CSS样式,请创建带有<style></style>标记的HTML文件,然后使用模板化HTML将单独的文件包含在索引文件中。

在上面的示例中,索引文件是模板化HTML,带有行:

<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
<?!= HtmlService.createHtmlOutputFromFile('JS_MainPageCode').getContent(); ?>