首页 > 解决方案 > 如何在 Google 脚本中上传文件到驱动器

问题描述

我有一个脚本,可让您从驱动器中选择一个文件到我的应用程序中。我希望能够从计算机而不是驱动器中选择文件,这可能吗?也许某种 htmlservice 可以做到这一点,但我不知道如何从中获取 blob 进行上传。

编辑:

包括在评论中提出的内容。使用以下代码,我确实将文件上传到了想要的文件夹中,但即使它已经上传,它也会挂在“上传中。请稍候......”。

代码.gs

function showPicker() {
  var html = HtmlService.createHtmlOutputFromFile('FileSelect.html')
      .setWidth(600)
      .setHeight(200)
      .setSandboxMode(HtmlService.SandboxMode.IFRAME);
  SpreadsheetApp.getUi().showModalDialog(html, 'Select a file');
}

function uploadTheFile(theForm) {
  Logger.log("TEST");
  Logger.log(theForm);
  var fileBlob=theForm.fileToLoad;
  Logger.log(fileBlob);
  var fldr = DriveApp.getFolderById('1dUfcChYwwSX3NLIEGg7g5MetpXfqu_pz');
  var file=fldr.createFile(fileBlob);
  var fi=formatFileName(file);
  var fileInfo={'name':fi.getName(),'type':fileBlob.getContentType(), 'size':fileBlob.getBytes(), 'folder':fldr.getName()};
  return fileInfo;
}

文件选择.html

<!DOCTYPE html>
<html>
  <head>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  function fileUploadJs(frmData) {
    document.getElementById('status').style.display ='inline';
    google.script.run
      .withSuccessHandler(updateOutput)
      .uploadTheFile(frmData)
  }

  function updateOutput(info)  {
    var br='<br />';
    var outputDiv = document.getElementById('status');
    outputDiv.innerHTML = br + 'File Upload Successful.' + br + 'File Name: ' + info.name + br + 'Content Type: ' + info.type + br + 'Folder Name: ' + info.folder;
  }

  console.log('My Code');
</script>
<style>
  body {background-color:#ffffff;}
  input{padding:2px;margin:2px;}
</style>

  </head>
  <body>
    <div id="formDiv">
      <form id="myForm">
        <input name="fileToLoad" type="file" /><br/>
        <input type="button" value="Submit" onclick="fileUploadJs(this.parentNode)" />
      </form>
    </div>
  <div id="status" style="display: none">
  <!-- div will be filled with innerHTML after form submission. -->
  Uploading. Please wait...
  </div>  
  <div id="controls">
      <input type="button" value="Close" onClick="google.script.host.close();" />
  </div>
</body>
</html>

标签: google-apps-scriptgoogle-sheets

解决方案


为了使解决方案按预期工作,我建议您对提供的代码进行以下更改:

  1. var fi=formatFileName(file);uploadTheFile()函数中删除,因为该formatFileName()方法不存在且不需要;

  2. 更新var fileInfo到这个:

var fileInfo={'name':file.getName(),'type':fileBlob.getContentType(), 'size':fileBlob.getBytes(), 'folder':fldr.getName()};

因此,基本上,formatFileName()您将直接使用file.getName()来检索文件名,而不是使用 。

此外,这里有一些链接可能会对您有所帮助:

  1. HtmlService 类

  2. Apps 脚本 Web 应用程序


推荐阅读