使用自定义表单将多个文件上传到Google云端硬盘并在电子表格中记录表单回复

时间:2017-10-18 18:37:19

标签: javascript google-apps-script

对于大型童子军阵营的组织,我目前正在尝试建立一个Web表单,其中可以提供服务请求(安全性,基础设施,材料等)。为此,我想要以下内容:

  • 将(多个)文件上传到Google云端硬盘文件夹

  • 将剩余的输入(文字,名称等)写入谷歌电子表格

  • 如果可能,请将文件位置的网址写入同一电子表格

到目前为止,我在结合前两个功能方面完全不成功。在整个过程中,我尝试了如下所述的方法的组合:

https://script.google.com/d/1x3p9ZAv-SafEK06r_Vr7fVuUNtEfBg1SGhmSYWjQ0kuPTk-y55a7Nink/edit?usp=sharing

Uploading Multiple Files to Google Drive with Google App Script

HTML form file upload to Google Drive and save URL to google sheet

Google Forms: Send data to spreadsheet

Google Forms file upload complete example

https://gist.github.com/xtman/060edd76c27b7fcb343dfb8e08252693

根据要求,我试图通过以下方式实现此目的: 实现两个功能的代码:

frm.submit(function () {
    allFiles = document.getElementById('supportingFiles').files;
    if (!frm.checkValidity || frm.checkValidity()) {
      if (allFiles.length == 0) {
        alert('Error: Please choose at least 1 file to upload.');
        google.script.run.record_Data(frm);
        return false;
      } else {
        frm.hide();
        alert('Step 1');
        var subfolderName = document.getElementById('requesterSubject').value;

        $.ajax({
          url: '',//URL of webhook endpoint for sending a Slack notification
          data: {
            title: subfolderName + ' is uploading screenshots',
            message: ''
          }
        });
        alert('Step 2');
        //google.script.run.withSuccesHandler(record_Data(transformedData).transformData('myForm');
        google.script.run.withSuccessHandler(afterSubfolderCreated).createSubfolder(subfolderName);
        alert('Step 3');
        return false;
      }
    } else {
      alert('Invalid form');
      return false;
    }
});

这是发生错误的地方。它能够按原样运行代码,但是当我尝试运行recordData函数时,它也没有做任何事情。

功能代码如下:
提交数据

function dataTransform(form){
  var transformedData = JSON.stringify( $(form).serializeArray() ); //  <-----------
  console.log( data );
  return transformedData; //don't submit
}

function recordData(e) {
  Logger.log(JSON.stringify(e)); // log the POST data in case we need to debug it
  try {
    var doc     = SpreadsheetApp.openById('some id');
    var sheet   = doc.getSheetByName('responses'); // select the responses sheet
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow()+1; // get next row
    var row     = [ new Date() ]; // first element in the row should always be a timestamp
    // loop through the header columns
    for (var i = 1; i < headers.length; i++) { // start at 1 to avoid Timestamp column
      if(headers[i].length > 0) {
        row.push(e.parameter[headers[i]]); // add data to row
      }
    }
    // more efficient to set values as [][] array than individually
    sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
  }
  catch(error) {
    Logger.log(e);
  }
  finally {
    return;
  }
}

提交文件

function uploadFileToDrive(base64Data, fileName, subfolderId) {
  Logger.log(subfolderId);
  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 subfolder = DriveApp.getFolderById(subfolderId);
    var file = subfolder.createFile(ss);
    Logger.log(file);
    return file.getName() + ' at ' + file.getUrl();
  } catch(e) {
    return 'createFile Error: ' + e.toString();
  }
}

function createSubfolder(subfolderName) {
  var dropbox = Utilities.formatDate(new Date(), "Europe/Amsterdam", "yyyy-MM-dd_hh.mm_") + subfolderName ;
  Logger.log(dropbox);
  var parentFolderId = "some folder id";
  var parentFolder = DriveApp.getFolderById(parentFolderId);
  var folder;
  try {
      folder = parentFolder.getFoldersByName(dropbox).next();      
  }
  catch(e) {
      folder = parentFolder.createFolder(dropbox);
  }
  Logger.log(folder);
  return folder.getId();
}
function afterSubfolderCreated(subfolderId) {
  console.log(subfolderId);
  console.log(allFiles);
  numUploads.total = allFiles.length;
  $('#progressbar').progressbar({ value: false });
  $(".progress-label").html('Preparing files for upload');
  for (var i = 0; i < allFiles.length; i++) {
    console.log(i);
    sendFileToDrive(allFiles[i], subfolderId);
  }
}

function sendFileToDrive(file, subfolderId) {
  var reader = new FileReader();
  reader.onload = function (e) {
    var content = reader.result;
    console.log('Sending ' + file.name);
    google.script.run.withSuccessHandler(updateProgressbar).uploadFileToDrive(content, file.name, subfolderId);
  }
  reader.readAsDataURL(file);
}

function updateProgressbar(idUpdate) {
  console.log('Received: ' + 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;
    $(".progress-label").text($(".progress-label").text() + ': FINISHED!');
    $("#progressbar").after('(Optional) Refresh this page if you want to fill out another request.');
    //<a href="javascript:window.top.location.href=window.top.location.href"> does not work
  }
}

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

1 个答案:

答案 0 :(得分:0)

我不了解代码,不够称职。但是,当您通过Google表单在电子表格中输入数据时,可以使用Autocrat插件来生成pdf文件的Google文档,该文档将通过电子邮件发送并保存到单个文件夹中。您也可以使用动态参考文件夹ID将文件一次保存到多个文件夹。您所要做的就是在电子表格中输入Google云端硬盘文件参考。如果您有数百个要链接的文件夹,它可能会很费力,但是我需要约100名学生来进行评估,因此效果很好。希望有帮助...