简体   繁体   English

如何使用外部 html 表单将文件上传到谷歌驱动器并将其他表单数据保存到谷歌表格?

[英]How do I make use of an external html form to upload file to google drive and save other form data to google sheets?

I am trying to adapt this tutorial: https://tanaikech.github.io/2020/08/13/uploading-file-to-google-drive-from-external-html-without-authorization/我正在尝试修改本教程: https://tanaikech.github.io/2020/08/13/uploading-file-to-google-drive-from-external-html-without-authorization/

that is specifically for uploading files to google drive, to include text field data to be saved in a google sheet.专门用于将文件上传到谷歌驱动器,以包含要保存在谷歌工作表中的文本字段数据。

Can any kind soul help me on this:(任何善良的灵魂都可以帮助我吗:(

This is what I have in my spread sheet:这是我的电子表格中的内容:

在此处输入图像描述

Here is the GAS code:这是气体代码:

    var sheetName = 'Sheet1'
    var scriptProp = PropertiesService.getScriptProperties()

    function intialSetup () {
      var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
      scriptProp.setProperty('key', activeSpreadsheet.getId())
    }

   function doPost(e) {

      const folderId = "root"; // Folder ID which is used for putting the file.
      const blob = Utilities.newBlob(
        JSON.parse(e.postData.contents),
        e.parameter.mimeType,
        e.parameter.filename
      );
  const file = DriveApp.getFolderById(folderId).createFile(blob);
  const responseObj = {
    filename: file.getName(),
    fileId: file.getId(),
    fileUrl: file.getUrl(),
  };

  var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
    var sheet = doc.getSheetByName(sheetName)

    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
    var range = sheet.getRange("A1:A").getValues();
    var filtered_r = range.filter(String).length;

    var newRow = headers.map(function(header) { // newRow is possibly a literally object where the keys are the headers and values are the user input
      if(header === "file"){
        e.parameter[header] = responseObj.fileUrl;
      }
      return e.parameter[header];
    })
  
    sheet.getRange(filtered_r + 1, 1, 1, newRow.length).setValues([newRow]);





  return ContentService.createTextOutput(
    JSON.stringify(responseObj)
  ).setMimeType(ContentService.MimeType.JSON);
}

Here is the external html code(not made in GAS project, which is why I cant use the google.script.run method)这是外部 html 代码(不是在 GAS 项目中制作的,这就是为什么我不能使用 google.script.run 方法的原因)

<form id="form">
  <input type="text" name="hobby">
  <input name="file" id="uploadfile" type="file" />
  <input id="submit" type="submit" />
</form>

<script>
  const form = document.getElementById("form");
  form.addEventListener("submit", (e) => {
    e.preventDefault();
    const file = form.file.files[0];
    const fr = new FileReader();
    fr.readAsArrayBuffer(file);
    fr.onload = (f) => {

        
      const url = "https://script.google.com/macros/s/###/exec"; // Please set the URL of Web Apps.

      const qs = new URLSearchParams({
        filename: file.name,
        mimeType: file.type,
      });

      
      fetch(`${url}?${qs}`, {
        method: "POST",
        body: JSON.stringify([...new Int8Array(f.target.result)]), // is it possible to change this value to  new FormData(form)?
      })
        .then((res) => res.json())
        .then(console.log)
        .catch(console.log);
    };
  });
</script>

I believe your goal is as follows.我相信你的目标如下。

  • You want to upload a file from <input name="file" id="uploadfile" type="file" /> and the value from <input type="text" name="hobby"> .您想从<input name="file" id="uploadfile" type="file" />上传文件和来自<input type="text" name="hobby">

When I saw your script, the file is sent to Web Apps.当我看到你的脚本时,文件被发送到 Web Apps。 But, value from <input type="text" name="hobby"> is not sent.但是,不会发送来自<input type="text" name="hobby">值。 I thought that this might be the reason for your issue.我认为这可能是您的问题的原因。 In order to remove this issue, the modified script is as follows.为了解决这个问题,修改后的脚本如下。

Modified script:修改后的脚本:

Google Apps Script side: Google Apps 脚本方面:

In this modification, doPost is modified.在这个修改中, doPost被修改。

function doPost(e) {
  const obj = JSON.parse(e.postData.contents);
  const folderId = "root"; // Folder ID which is used for putting the file.
  const blob = Utilities.newBlob(
    obj.file,
    e.parameter.mimeType,
    e.parameter.filename
  );
  const file = DriveApp.getFolderById(folderId).createFile(blob);
  const responseObj = {
    filename: file.getName(),
    fileId: file.getId(),
    fileUrl: file.getUrl(),
  };
  obj.file = responseObj.fileUrl;
  var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
  var sheet = doc.getSheetByName(sheetName)
  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
  var range = sheet.getRange("A1:A").getValues();
  var filtered_r = range.filter(String).length;
  var newRow = headers.map(function (header) {
    return obj[header];
  });
  sheet.getRange(filtered_r + 1, 1, 1, newRow.length).setValues([newRow]);
  return ContentService.createTextOutput(
    JSON.stringify(responseObj)
  ).setMimeType(ContentService.MimeType.JSON);
}

HTML & Javascript side: HTML & Javascript 方面:

<form id="form">
  <input type="text" name="hobby" id="sample" /> <!-- Modified -->
  <input name="file" id="uploadfile" type="file" />
  <input id="submit" type="submit" />
</form>

<script>
  const form = document.getElementById("form");
  form.addEventListener("submit", (e) => {
    e.preventDefault();
    const file = form.file.files[0];
    const fr = new FileReader();
    fr.readAsArrayBuffer(file);
    fr.onload = (f) => {
      const url = "https://script.google.com/macros/s/###/exec"; 
      const qs = new URLSearchParams({
        filename: file.name,
        mimeType: file.type,
      });
      fetch(`${url}?${qs}`, {
        method: "POST",
        body: JSON.stringify({file: [...new Int8Array(f.target.result)], hobby: document.getElementById("sample").value}),
      })
        .then((res) => res.json())
        .then(console.log)
        .catch(console.log);
    };
  });
</script>

Note:笔记:

Please share a with multiple text fields and also multiple Upload files option using HTML external with google script code.请使用 HTML 外部与谷歌脚本代码共享多个文本字段和多个上传文件选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM