0

I am writing a large file uploader for Google Drive and when I tried to implement writing some data to a Google Sheet I ran into a brick wall, for whatever reason I could not get it to ever write or even give a error as to why. I decided to start a whole new project and made it as simple as possible so all it does is grab similar data to what I will be grabbing and write it, but still no luck. I am not super familiar with the Google Apps processes or the syntax of using them so I am probably just doing something really stupid.

Old code removed

I have tried removing some variables like file and email in case they needed to be written differently and changing how the form is passed to the function but the best I ever got was a "Cannot read Null" error when I passed it a form that didn't exist.

UPDATE:

Once I had it working I tried to slip it into the main script I am using (Which is basically a copy of this but now its not working, I am realizing this may be over my head unfortunately cause no matter what I try its doing the same, runs and uploads the file fine, but does not update the form. Google Scripts:

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

function getAuth() {
  return { accessToken: ScriptApp.getOAuthToken(), folderId: "1sFxs3Ga4xWFCgIXRUnQzCAAp_iRX-wdj" };
}

function setDescription({fileId, description}) {
  DriveApp.getFileById(fileId).setDescription(description);
}


function updateform(formObject) {
  try {
    var ss = SpreadsheetApp.openById('1iCTNZ6RERnes1Y-ocfXzPN3jviwdIEK_dBKQ4LIu5KI');
    var sheet = ss.getSheets()[0];
    sheet.appendRow([myFile.getName(), myFile.getUrl(), formObject.myName], "If This Shows Up It Worked");
  } catch (error) {
    return error.toString();
  }
}

HTML:

<form id="myForm" align="center" onsubmit="updatesheet(This)">
  <input type="text" name="myName" placeholder="Your name..">
  <input type="file" name="myFile">
  <input type="submit" value="Submit Form" onclick="run(); return false;">                 
</form>
<div id="progress"></div>
<div id="output"></div>
<script src="https://cdn.jsdelivr.net/gh/tanaikech/ResumableUploadForGoogleDrive_js@master/resumableupload_js.min.js"></script>
<script>
function onSuccess() {
  var div = document.getElementById('output');
  div.innerHTML = '<a href="Spreadsheet Updated</a>';
}

function onFailure(error) {
  alert(error.message);
}
function updatesheet(form) {
  google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).updateform(form); 
}

function run() {       
  google.script.run.withSuccessHandler(accessToken => ResumableUploadForGoogleDrive(accessToken)).getAuth();
}

function ResumableUploadForGoogleDrive({accessToken, folderId}) {
  const myName = document.getElementsByName("myName")[0].value;
  const file = document.getElementsByName("myFile")[0].files[0];
  if (!file) return;
  let fr = new FileReader();
  fr.fileName = file.name;
  fr.fileSize = file.size;
  fr.fileType = file.type;
  fr.readAsArrayBuffer(file);
  fr.onload = e => {
    var id = "p";
    var div = document.createElement("div");
    div.id = id;
    document.getElementById("progress").appendChild(div);
    document.getElementById(id).innerHTML = "Initializing.";
    const f = e.target;
    const resource = { fileName: f.fileName, fileSize: f.fileSize, fileType: f.fileType, fileBuffer: f.result, accessToken, folderId };
    const ru = new ResumableUploadToGoogleDrive();
    ru.Do(resource, function (res, err) {
      if (err) {
        console.log(err);
        return;
      }
      console.log(res);
      let msg = "";
      if (res.status == "Uploading") {
        msg = Math.round((res.progressNumber.current / res.progressNumber.end) * 100) + "% (" + f.fileName + ")";
      } else {
        msg = res.status + " (" + f.fileName + ")";
      }
      if (res.status == "Done") {
        google.script.run.withSuccessHandler(_ => {
          document.getElementById('myForm').style.display = 'none';
          document.getElementById('p').style.display = 'none';
          document.getElementById('output').innerHTML = "All information submitted, thank you!";
        }).setDescription({fileId: res.result.id, description: "Uploaded by " + myName});
      }
      document.getElementById(id).innerText = msg;
    });
  }
}
</script>

1 Answers1

3

Several things about your updated code.

First it should be this not This.

Second you have onsubmit and onclick events for the same form. I believe the onclick is suppressing the submit event. Remove onclick entirely.

Third you use a try catch block in updateform so withFailureHandler will never execute. Instead the error message or null is returned to the success handler onSuccess(error).

Forth, I use a paragraph <p> instead of an anchor <a>. The href is malformed in your anchor.

Last, run() can be executed in updatesheet(form). Note run() is asynchronous which means it doesn't wait for google.script.run to finish before executing.

I can simply tell you that all the alerts are displayed and the execution log shows updateform did execute. So this code works for me.

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <form id="myForm" align="center" onsubmit="updatesheet(this)">
      <input type="text" name="myName" placeholder="Your name..">
      <input type="text" name="myFile">
      <input type="submit" value="Submit Form">                 
    </form>
    <div id="progress"></div>
    <div id="output"></div>
    <script>
      function onSuccess(error) {
        if( error ) {
          alert(err);
          return;
        }
        alert("onSuccess");
        var div = document.getElementById('output');
        div.innerHTML = "<p>Spreadsheet Updated</p>";
      }

      function run() {
        alert("run");   
      }

      function updatesheet(form) {
        alert("updatesheet");
        google.script.run.withSuccessHandler(onSuccess).updateform(form);
        run();
      }
    </script>
  </body>
</html>
TheWizEd
  • 7,517
  • 2
  • 11
  • 19
  • I ran into the same thing with the changing of the submit button value a couple days ago, hence why I started putting it directly inside the onclick event. But even this code didn't work for me (No errors like my code before, but also no output). I finally made a new file and things started working so I put it down to a cache issue or possibly an issue with the authorization. – Tristan.Beer Feb 18 '23 at 17:49
  • I copied your code from SO to my script editor. Things didn't work so I basically retyped from scratch and it started working I wonder if there was some unseen character in the code that was preventing it from working. – TheWizEd Feb 18 '23 at 19:24
  • I wonder that as well, I have updated my question as now that I have tried to implement it again its doing the exact same thing but this time a new file didn't work for me. I have checked all the permissions and even updated the appscripts.json to include the needed scopes but nothing. Don't like not being able to tell if its me or the server doing something wrong. – Tristan.Beer Feb 18 '23 at 20:05
  • Thanks for all your help, I made the changes you suggested and everything is at least triggering now for sure. For whatever reason I cant run the ResumableUploadForGoogleDrive from a function trigger on a onSubmit event without a constructor error and I dont understand that part of the code enough to mess with it right now. But your help has been invaluable and pointed me in the right direction for sure! – Tristan.Beer Feb 21 '23 at 13:33