如何使用Google Scripts将html表单数据保存到Google电子表格中?

时间:2015-03-26 10:30:01

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

我想创建一个HTML,CSS表单(如Google表单),我想通过它接受文本数据以及文件(如图像和文档)。我正在使用Google Script。这是 form.html文件

<!-- Include the Google CSS package -->
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/addons.css">

<form id="myForm">
<input type="text" name="myName" placeholder="Your name..">
<input type="file" name="myFile">
<input type="submit" value="Upload File" 
       onclick="this.value='Uploading..';
                google.script.run.withSuccessHandler(fileUploaded)
                .uploadFiles(this.parentNode);
                return false;
                google.script.run.withSuccessHandler(fileUploaded)
                .doPost(this.parentNode);">
</form>

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

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

<style>
input { display:block; margin: 20px; }
</style>

和server.gs

function doGet(e)
{
  return HtmlService.createHtmlOutputFromFile('form.html');
}
var url;

function uploadFiles(form) 
{
  try {

    var dropbox = "Student Files";
    var folder, folders = DriveApp.getFoldersByName(dropbox);

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

    var blob = form.myFile;    
    var file = folder.createFile(blob);    
    file.setDescription("Uploaded by " + form.myName);
    url=file.getUrl();
    return "File uploaded successfully " + file.getUrl(); 
  } 
  catch (error) 
  {  
    return error.toString();
  }
}
function doPost(form) { // change to doPost(e) if you are recieving POST data
  var name = form.myName;
  var message = 'Ram';
  var submissioSSKey = 'ID';
  var sheet = SpreadsheetApp.openById(submissioSSKey).getActiveSheet();
  var lastRow = sheet.getLastRow();
  var targetRange = sheet.getRange(lastRow+1, 1, 1, 2).setValues([[name,url]]);
}

上传的文件存储在我的Google云端硬盘中,但文字数据未存储在电子表格中

2 个答案:

答案 0 :(得分:1)

您还可以使用Cloudstitch的Magic Form实用程序,该实用程序为您的电子表格创建一个特殊的URL,您只需向(或通过Ajax)发送普通的POST请求即可。这样您就不必担心所有客户端API。

http://www.cloudstitch.com/project-templates/magic-form

答案 1 :(得分:0)

删除return false;。你没有执行doPost ...