使用 Google Apps 脚本处理来自数组中输入元素的多个文件

Handling multiple files from an input element in an array with Google Apps Script

我有一个表单,允许从下拉列表中 select 一个项目并上传一个文件。项目的名称和 ID 保存在电子表格文档中。适用于一个文件...但我想上传多个文件。你能帮我修复脚本吗?

HTML 部分看起来像这样

<div class="col-md-4 col-sm-6 ">
           <div class="caption">
             <h3>Bildauswahl</h3>
             <p align="center"><input type="file" name="myFiles[]" id="myFiles" multiple></p>
         </div>
         </div>

我的脚本如下:

var dropBoxId = "XYZ"; 
var logSheetId = "ABC";

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('InputForm.html');
}

function uploadFiles(formObject) {
  try {
    // Create a file in Drive from the one provided in the form
    var folder = DriveApp.getFolderById(dropBoxId);
    var input = document.getElementById('myFiles');

    for (i = 0; i<input.files.length; i++) {
      var blob = input.files[i];
      var file = folder.createFile(blob);
      var ss = SpreadsheetApp.openById(logSheetId);
      var sheet = ss.getSheets()[0];
      sheet.appendRow([file.getName(), file.getUrl(), formObject.myName]);
    }


    // Return the new file Drive URL so it can be put in the web app output
    return file.getUrl();
  } catch (error) {
    return error.toString();
  }
}

谢谢。

截至目前,您必须使用变通方法来处理多个文件。 multiple 属性仅在 IFRAME 模式下有效,但文件输入在 IFRAME 模式下会被破坏。

要查看此解决方法,请查看针对此问题提交的错误: https://code.google.com/p/google-apps-script-issues/issues/detail?id=4610

此外,在您的代码中,您混合了服务器端和客户端代码,这些代码将不起作用:

var folder = DriveApp.getFolderById(dropBoxId); //server side
var input = document.getElementById('myFiles'); //client side

您需要在客户端进行多文件处理

我想出了一个很好的多文件上传解决方案。限制是文件必须小于 10 MB。

CODE.GS

function doGet() {
 return HtmlService.createHtmlOutputFromFile('index').setSandboxMode(HtmlService.SandboxMode.IFRAME);

}

function saveFile(data,name,folderId) {

var contentType = data.substring(5,data.indexOf(';'));
var file = Utilities.newBlob(Utilities.base64Decode(data.substr(data.indexOf('base64,')+7)), contentType, name);
  DriveApp.getFolderById(folderId).createFile(file);

}

index.html

<div>
 <input type="file"  id="myFiles" name="myFiles" multiple/>
 <input type="button" value="Submit" onclick="SaveFiles()" />
</div>

<script>

  var reader = new FileReader();
  var files;
  var fileCounter = 0;
  var folderId = "";




  reader.onloadend = function () {
   google.script.run
    .withSuccessHandler(function(){
      fileCounter++;      
      postNextFile();
    }).saveFile(reader.result,files[fileCounter].name,folderId);

  }



function SaveFiles(){
  var folderSelect = document.getElementById("folderSelectId");
  folderId = folderSelect.options[e.selectedIndex].value;
  files = document.getElementById("myFiles").files;  
  postNextFile();
 }


function postNextFile(){if(fileCounter < files.length){reader.readAsDataURL(files[fileCounter]);}else{fileCounter=0;alert("upload done")}}

</script>