在Google Apps脚本中,努力获取来自HTML表单的文本输入以记录在电子表格中。

huangapple go评论78阅读模式
英文:

Struggling to capture the text input of an html form from Google Apps Scripts to log on a spreadsheet

问题

-----更新后的工作代码在底部-----

-----更新的[Git链接](https://gist.github.com/4n7h0ny/a5e89916dfa596e0b1831347b478ec4e) --------

我有一个目前正常工作的 Google Apps 脚本,它允许批量上传文件而无需登录,将文件上传到 Google Drive,并在电子表格上记录文件信息。我还想从 HTML 表单中捕获文本输入字段。在过去的两周里我一直在努力,但一直没有取得任何进展,任何帮助都将不胜感激。

我创建了一个 Git [链接](https://gist.github.com/4n7h0ny/c879c72888db1a2cd891f6f83db7e332)

Web 应用链接 - https://script.google.com/macros/s/AKfycby59WOCrFAUhM3o13PGiDPMyrkp9qeFhuqKnoSJBHTn6rBOfJroue29TU-lgxlsgRAX6g/exec

我想捕获 HTML 表单中的这部分:

```html
type  <TEXTAREA name="projectDescription" 
          id="projectDesctiptionIndex"
          placeholder="Index"
          style ="width:400px; height:200px;"
          ></TEXTAREA>here

Code.gs 代码:

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

var sid = '1eQIZESbrhst6FUza8t_SEwy5bnKBTarNwDDuIVKsLiw';  //Google 表格的 ID

function uploadFileToDrive(base64Data, fileName) {
  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 folder = DriveApp.getFolderById("1h7hMHz7XD1oFKFY_jotrcVdq6Bn0uXfY");  //Google Drive 文件夹的 ID

    var file = folder.createFile(ss);

    console.log(file);

    var ssss = SpreadsheetApp.openById(sid).getSheetByName("Sheet1");
    ssss.appendRow([file.getName(), file.getUrl(), Date()]);

    return file.getName();
  }catch(e){
    return 'Error: ' + e.toString();
  }
}

form.html 代码:

<body>
  <div id="formcontainer">


    <br><br>


    <form id="myForm"> 
      <div>


      </div>
      <div>

      <label for="fileText" id="fileTextIndex">Index:</label>

          <TEXTAREA name="projectDescription" 
          id="projectDesctiptionIndex"
          placeholder="Index"
          style ="width:400px; height:200px;"
          ></TEXTAREA>


      </div> 
      <br>



      <label for="myFile">Upload Attachment(s):</label>
      <br>


      <input type="file" name="filename" id="myFile" multiple>

      <input type="button" value="Submit" onclick="iteratorFileUpload()">


    </form>
  </div>

  <div id="output"></div>
<div id="progressbar">
    <div class="progress-label"></div>
</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

<script>

var numUploads = {};
numUploads.done = 0;
numUploads.total = 0;

// 将文件上传到 Drive 文件夹中
// 这被设置为将它们全部发送到一个文件夹中(在.gs 文件中指定)
function iteratorFileUpload() {
    var allFiles = document.getElementById('myFile').files;

    if (allFiles.length == 0) {
        alert('No file selected!');
    } else {
        // 显示进度条

        numUploads.total = allFiles.length;
        $('#progressbar').progressbar({
        value : false
        });//.append("<div class='caption'>37%</div>");
        $(".progress-label").html('Preparing files for upload');
        // 逐个发送文件
        for (var i = 0; i < allFiles.length; i++) {
            console.log(i);
            sendFileToDrive(allFiles[i]);
        }
    }
}

function sendFileToDrive(file) {
        var reader = new FileReader();
    reader.onload = function (e) {
        var content = reader.result;
        console.log('Sending ' + file.name);
        var currFolder = 'Something';
          
        google.script.run.withSuccessHandler(updateProgressbar).uploadFileToDrive(content, file.name, currFolder);
    }
    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;
   };
}
</script>

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

  </script>

  <style>
    body {
      max-width: 400px;
      padding: 20px;
      margin: auto;
    }
    input {
      display: inline-block;
      width: 100%;
      padding: 5px 0px 5px 5px;
      margin-bottom: 10px;
      -webkit-box-sizing: border-box;
      ‌​ -moz-box-sizing: border-box;
      box-sizing: border-box;
    }
    select {
      margin: 5px 0px 15px 0px;
    }
    input[type="submit"] {
      width: auto !important;
      display: block !important;
    }
    input[type="file"] {
      padding: 5px 0px 15px 0px !important;
    }
#progressbar{
    width: 100%;
    text-align: center;
    overflow: hidden;
    position: relative;
   

<details>
<summary>英文:</summary>

-----Updated working code is on the bottom-----

-----Updated [Git Here](https://gist.github.com/4n7h0ny/a5e89916dfa596e0b1831347b478ec4e) --------

I have a google apps script that is currently working that allows bulk file uploads without a log in, uploads the files to a drive, and logs the file info on a spreadsheet.  I also want to capture a text input field from the html form to capture that as well.  I have been struggling over the past two weeks and have made zero progress on the matter, any help would be greatly appreciated.

I have made a git  https://gist.github.com/4n7h0ny/c879c72888db1a2cd891f6f83db7e332

webapp url - https://script.google.com/macros/s/AKfycby59WOCrFAUhM3o13PGiDPMyrkp9qeFhuqKnoSJBHTn6rBOfJroue29TU-lgxlsgRAX6g/exec

I want to capture this part of the html form 

type <TEXTAREA name="projectDescription"
id="projectDesctiptionIndex"
placeholder="Index"
style ="width:400px; height:200px;"
></TEXTAREA>here


Code.gs code

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

var sid = &#39;1eQIZESbrhst6FUza8t_SEwy5bnKBTarNwDDuIVKsLiw&#39;;  //URL OF GOOGLE SHEET;

function uploadFileToDrive(base64Data, fileName) {
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 folder = DriveApp.getFolderById(&quot;1h7hMHz7XD1oFKFY_jotrcVdq6Bn0uXfY&quot;);
var file = folder.createFile(ss);
console.log(file);
var ssss = SpreadsheetApp.openById(sid).getSheetByName(&quot;Sheet1&quot;);
ssss.appendRow([file.getName(), file.getUrl(), Date()]);
return file.getName();

}catch(e){
return 'Error: ' + e.toString();
}
}


form.html code

<body>
<div id="formcontainer">

&lt;br&gt;&lt;br&gt;
&lt;form id=&quot;myForm&quot;&gt; 
&lt;div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;label for=&quot;fileText&quot; id=&quot;fileTextIndex&quot; &gt;Index:&lt;/label&gt;
&lt;TEXTAREA name=&quot;projectDescription&quot; 
id=&quot;projectDesctiptionIndex&quot;
placeholder=&quot;Index&quot;
style =&quot;width:400px; height:200px;&quot;
&gt;&lt;/TEXTAREA&gt;
&lt;/div&gt; 
&lt;br&gt;
&lt;label for=&quot;myFile&quot;&gt;Upload Attachment(s):&lt;/label&gt;
&lt;br&gt;
&lt;input type=&quot;file&quot; name=&quot;filename&quot; id=&quot;myFile&quot; multiple&gt;
&lt;input type=&quot;button&quot; value=&quot;Submit&quot; onclick=&quot;iteratorFileUpload()&quot;&gt;
&lt;/form&gt;

</div>

<div id="output"></div>
<div id="progressbar">
<div class="progress-label"></div>
</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

<script>

var numUploads = {};
numUploads.done = 0;
numUploads.total = 0;

// Upload the files into a folder in drive
// This is set to send them all to one folder (specificed in the .gs file)
function iteratorFileUpload() {
var allFiles = document.getElementById('myFile').files;

if (allFiles.length == 0) {
alert(&#39;No file selected!&#39;);
} else {
//Show Progress Bar
numUploads.total = allFiles.length;
$(&#39;#progressbar&#39;).progressbar({
value : false
});//.append(&quot;&lt;div class=&#39;caption&#39;&gt;37%&lt;/div&gt;&quot;);
$(&quot;.progress-label&quot;).html(&#39;Preparing files for upload&#39;);
// Send each file at a time
for (var i = 0; i &lt; allFiles.length; i++) {
console.log(i);
sendFileToDrive(allFiles[i]);
}
}

}

function sendFileToDrive(file) {
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;
console.log('Sending ' + file.name);
var currFolder = 'Something';

    google.script.run.withSuccessHandler(updateProgressbar).uploadFileToDrive(content, file.name, currFolder);
}
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 ){
//uploadsFinished();
numUploads.done = 0;
};
}
</script>

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

</script>

<style>
body {
max-width: 400px;
padding: 20px;
margin: auto;
}
input {
display: inline-block;
width: 100%;
padding: 5px 0px 5px 5px;
margin-bottom: 10px;
-webkit-box-sizing: border-box;
‌​ -moz-box-sizing: border-box;
box-sizing: border-box;
}
select {
margin: 5px 0px 15px 0px;
}
input[type="submit"] {
width: auto !important;
display: block !important;
}
input[type="file"] {
padding: 5px 0px 15px 0px !important;
}
#progressbar{
width: 100%;
text-align: center;
overflow: hidden;
position: relative;
vertical-align: middle;

}
.progress-label {
float: left;
margin-top: 5px;
font-weight: bold;
text-shadow: 1px 1px 0 #fff;
width: 100%;
height: 100%;
position: absolute;
vertical-align: middle;
}
</style>
</body>


I have tried using the 

document.getElementById('projectDesctiptionIndex').innerHTLM = PROJECTDESCRIPTION


but I do not understand this method enough to pull back to the JS side of things and after 80+ iterations of failure this is something I simply can not figure out on my own as of now.
---------------Updated working code that logs everything with a huge thank you to Tanaike for helping me keep my sanity and get through this wall I hit. -----------------

Code.gs

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

var sid = &#39;1eQIZESbrhst6FUza8t_SEwy5bnKBTarNwDDuIVKsLiw&#39;;  //ID OF GOOGLE SHEET;

function uploadFileToDrive(base64Data, fileName,textY, textIndex, textDescription) {
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 folder = DriveApp.getFolderById(&quot;1h7hMHz7XD1oFKFY_jotrcVdq6Bn0uXfY&quot;);  //Google Drive folder ID of the folder the files get uploaded to
var file = folder.createFile(ss);
console.log(file);
var ssss = SpreadsheetApp.openById(sid).getSheetByName(&quot;Sheet4&quot;);
console.log(decodeURI(textDescription));
ssss.appendRow([file.getName(), file.getUrl(), Date(), file.getId(), &quot;0&quot;, textDescription, textIndex]);
return file.getName();
}catch(e){
return &#39;Error: &#39; + e.toString();

}

}


form.html

<body>
<div id="formcontainer">

&lt;form id=&quot;myForm&quot;&gt; 
&lt;br&gt;
&lt;div&gt;
&lt;label for=&quot;projectDescription&quot; &gt;Index:&lt;/label&gt;
&lt;input type=&quot;text&quot; name=&quot;projectDescription1&quot; id=&quot;idIndex&quot; placeholder=&quot;Index&quot;&gt;
&lt;label for=&quot;projectDescription555&quot; &gt;Description:&lt;/label&gt;
&lt;input type=&quot;text&quot; name=&quot;projectDescription5551&quot; id=&quot;idText&quot; placeholder=&quot;Description&quot;&gt;
&lt;/div&gt;
&lt;!-- &lt;label for=&quot;myFile&quot;&gt;Upload Attachment(s):&lt;/label&gt; --&gt;
&lt;br&gt;
&lt;input type=&quot;file&quot; name=&quot;filename&quot; id=&quot;myFile&quot; multiple&gt;
&lt;input type=&quot;button&quot; value=&quot;Submit&quot; onclick=&quot;iteratorFileUpload()&quot;&gt;
&lt;/form&gt;

</div>

<div id="output"></div>
<div id="progressbar">
<div class="progress-label"></div>
</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

<script>

var numUploads = {};
numUploads.done = 0;
numUploads.total = 0;

// Upload the files into a folder in drive
// This is set to send them all to one folder (specificed in the .gs file)
function iteratorFileUpload() {
var allFiles = document.getElementById('myFile').files;

if (allFiles.length == 0) {
alert(&#39;No file selected!&#39;);
} else {
//Show Progress Bar
numUploads.total = allFiles.length;
$(&#39;#progressbar&#39;).progressbar({
value : false
});//.append(&quot;&lt;div class=&#39;caption&#39;&gt;37%&lt;/div&gt;&quot;);
$(&quot;.progress-label&quot;).html(&#39;Preparing files for upload&#39;);
// Send each file at a time
for (var i = 0; i &lt; allFiles.length; i++) {
console.log(i);
sendFileToDrive(allFiles[i]);
}
}

}

function sendFileToDrive(file) {
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;
console.log('Sending ' + file.name);
var currFolder = 'Something';
var textIndex = document.getElementById("idIndex").value;
var textDescription = document.getElementById("idText").value;
var textY = document.getElementById("idText").value;

    google.script.run.withSuccessHandler(updateProgressbar).uploadFileToDrive(content, file.name, currFolder, textIndex, textDescription, textY);
}
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 ){

var text = document.getElementById("idText").value;
var text1 = document.getElementById("idIndex").value;
google.script.run.putText(text, text1);

uploadsFinished();
numUploads.done = 0;
};

// if( numUploads.done == numUploads.total ){
// //uploadsFinished();
// numUploads.done = 0;
// };
}
</script>

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

</script>

<style>
body {
max-width: 400px;
padding: 20px;
margin: auto;
}
input {
display: inline-block;
width: 100%;
padding: 5px 0px 5px 5px;
margin-bottom: 10px;
-webkit-box-sizing: border-box;
‌​ -moz-box-sizing: border-box;
box-sizing: border-box;
}
select {
margin: 5px 0px 15px 0px;
}
input[type="submit"] {
width: auto !important;
display: block !important;
}
input[type="file"] {
padding: 5px 0px 15px 0px !important;
}
#progressbar{
width: 100%;
text-align: center;
overflow: hidden;
position: relative;
vertical-align: middle;

}
.progress-label {
float: left;
margin-top: 5px;
font-weight: bold;
text-shadow: 1px 1px 0 #fff;
width: 100%;
height: 100%;
position: absolute;
vertical-align: middle;
}
</style>
</body>


</details>
# 答案1
**得分**: 1
Here is the translated content:
```
从您的回复中,我相信您的目标如下。
- 当通过点击按钮上传文件时,您也希望将文本区域标签中的文本放入电子表格中。
在这种情况下,对以下修改如何?在此修改中,JavaScript 和 Google Apps Script 都进行了修改。
### JavaScript 部分:
请将 JavaScript 中的函数 `updateProgressbar` 修改如下。
#### 从:
if( numUploads.done == numUploads.total ){
//uploadsFinished();
numUploads.done = 0;
};
#### 至:
if( numUploads.done == numUploads.total ){
// 我添加了下面的脚本。
var text = document.getElementById("projectDesctiptionIndex").value;
google.script.run.putText(text);
//uploadsFinished();
numUploads.done = 0;
};
### Google Apps Script 部分:
请将以下函数添加到 Google Apps Script 中。
function putText(text) {
var sheet = SpreadsheetApp.openById(sid).getSheetByName("Sheet1");
sheet.getRange("D" + sheet.getLastRow()).setValue(text);
}
- 通过上述修改,当您设置文件并在文本区域标签中输入值后点击“提交”按钮时,文件将被上传,并且输入的文本将放入“D”列中。
- 在您显示的示例图像中,似乎您希望将文本放在“C”列中。但是,在您的脚本中,“C”列似乎是日期。因此,我将文本放在“D”列中。请注意这一点。
## 注意:
- **当您修改了 Web Apps 的 Google Apps Script 时,请将部署为新版本。通过这样做,修改后的脚本将反映在 Web Apps 中。请注意这一点。**
- 您可以在我的报告“[在新 IDE 中重新部署 Web Apps 而不更改 Web Apps 的 URL(作者:我)](https://gist.github.com/tanaikech/ebf92d8f427d02d53989d6c3464a9c43)”中查看此详细信息。
```
<details>
<summary>英文:</summary>
From your reply, I believe your goal is as follows.
- When the files are uploaded by clicking a button, you want to also put the text of the text area tag to Spreadsheet.
In this case, how about the following modification? In this modification, both Javascript and Google Apps Script are modified.
### Javascript side:
Please modify the function `updateProgressbar` of Javascript as follows.
#### From:
if( numUploads.done == numUploads.total ){
//uploadsFinished();
numUploads.done = 0;
};
#### To:
if( numUploads.done == numUploads.total ){
// I added the below script.
var text = document.getElementById(&quot;projectDesctiptionIndex&quot;).value;
google.script.run.putText(text);
//uploadsFinished();
numUploads.done = 0;
};
### Google Apps Script side:
Please add the following function to Google Apps Script.
function putText(text) {
var sheet = SpreadsheetApp.openById(sid).getSheetByName(&quot;Sheet1&quot;);
sheet.getRange(&quot;D&quot; + sheet.getLastRow()).setValue(text);
}
- By the above modification, when you set the files and a value to the text area tag and click &quot;Submit&quot; button, the files are uploaded and the inputted text is put into column &quot;D&quot;.
- In your showing sample image, it seems that you want to put the text in column &quot;C&quot;. But, in your script, it seems that column &quot;C&quot; is the date. So, I put the text in column &quot;D&quot;. Please be careful about this.
## Note:
- **When you modified the Google Apps Script of Web Apps, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful about this.**
- You can see the detail of this in my report &quot;[Redeploying Web Apps without Changing URL of Web Apps for new IDE (Author: me)](https://gist.github.com/tanaikech/ebf92d8f427d02d53989d6c3464a9c43)&quot;.
</details>

huangapple
  • 本文由 发表于 2023年4月11日 05:26:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75980874.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定