1
votes

To preface, I'm super new to programming in general, nevermind javascript.

I'm developing a web application where a user can upload a picture by clicking on a button. This action will upload pictures into a certain directory in my google drive with a unique folder and name.

Now, I'm trying to copy and paste the google drive link of a picture any time it has been uploaded.

I am able to successfully get the ID of the picture URL in my getFileUrl() method. But when I call that method within my doStuff1() function then later insert that info into userInfo.fileUrl, I am getting https://docs.google.com/document/d/undefined/ as the output in my spreadsheet. How can call that value?

Updated: I am realizing that when I use "google.script.run.getFileUrl("fn","i"), that is when I'm getting "undefined". When I run the getFileUrl() function locally, I do get the value that I want. Please advise how I can use .WithSuccessHandler(function) correctly so that I can return the value of "fileId0".


This is the front end, where a user uploads the picture

page.html

  <html>
  <head> 
   <body>
   <form action="#" method="post" enctype="multipart/form-data">
   <div class="row">
     <div class="file-field input-field">
        <div class="waves-effect waves-light btn-small">
          <i class="material-icons right">insert_photo</i>
          <span>Import Picture</span>
          <input id="files" type="file" name="image">
        </div>

        <div class="file-path-wrapper">
            <input disabled selected type="text" class="file-path 
             validate" placeholder="Choose an image">
        </div>
     </div>
  </div>
  </form>

 <?!= include("page-js"); ?>

</div> <!-- CLOSE CONTAINER-->


 </body>
</html>

This is part of the javascript to put relevant info in an array, which will later be used to append a row in the google sheet

page-js.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>    
 <script src="https://gumroad.com/js/gumroad.js"></script>


 <script>
document.getElementById("addAnother").addEventListener("click",doStuff1);



    var i=1;
    var num={};


    function doStuff1(){

       num.picNum2=i;
       var personName=document.getElementById("fn").value;

       var fileId00=google.script.run.getFileUrl("fn","i");

       var userInfo ={};

       userInfo.firstName= document.getElementById("fn").value;
       userInfo.number=i;
       userInfo.fileUrl="https://docs.google.com/document/d/"+fileId00 
       +"/";


       i++;

       google.script.run.userClicked(userInfo);

    }

This is part of the javascript to upload picture file into the Google drive

(still part of page-js.html)

  var file, 
  reader = new FileReader();
  var today = new Date();
  var date = today.getFullYear()+'-'+(today.getMonth()+1)+'- '+today.getDate();

  reader.onloadend = function(e) {
    if (e.target.error != null) {
      showError("File " + file.name + " could not be read.");
      return;
    } else {
      google.script.run
        .withSuccessHandler(showSuccess)
   .uploadFileToGoogleDrive(e.target.result,num.picNum,date,$('input#fn')
   .val(),$('input#date').val());

    }
  };

   function showSuccess(e) {
    if (e === "OK") { 
      $('#forminner').hide();
      $('#success').show();
    } else {
      showError(e);
    }
  }


     function submitForm() {


    var files = $('#files')[0].files;

    if (files.length === 0) {
      showError("Please select a image to upload");
      return;
    }

    file = files[0];

    if (file.size > 1024 * 1024 * 5) {
      showError("The file size should be < 5 MB.");
      return;
    }

    showMessage("Uploading file..");

    reader.readAsDataURL(file);


  }

        function showError(e) {
    $('#progress').addClass('red-text').html(e);
  }

  function showMessage(e) {
    $('#progress').removeClass('red-text').html(e);
  }

 </script>

This part grabs the array "userInfo" and appends the content in a row within a designated google sheet. Any time, I click on the button in the front end, it creates a new row.

Code.gs

  //google sheet web script

    var url="https://docs.google.com/spreadsheets/d/XXXXX";

   function getFileUrl(fn,i){

  try{
      var today0 = new Date();
       var date0 = today0.getFullYear()+'-'+(today0.getMonth()+1)+'-' 
       +today0.getDate();

      var dropbox0 = "OE Audit Pictures";
      var folder0,folders0 = DriveApp.getFoldersByName(dropbox0);

     while (folders0.hasNext())
       var folder0=folders0.next();

      var dropbox20=[date0,fn].join(" ");


      var folder20,folders20=folder0.getFoldersByName(dropbox20);
      while (folders20.hasNext())
         var folder20=folders20.next();


         var file0, files0= folder20.getFilesByName(i);
      while (files0.hasNext())
        var file0=files0.next();


        var fileId0=file0.getUrl();


       return fileId0;
          }  catch(f){
  return f.toString();
        }
    }


  function userClicked(userInfo){

     var ss= SpreadsheetApp.openByUrl(url);
     var ws=ss.getSheetByName("Data");
      ws.appendRow([userInfo.number,new Date(), 
         userInfo.firstName,userInfo.fileUrl]);

      }

   function include(filename){
      return HtmlService.createHtmlOutputFromFile(filename).getContent();  
    }


  function uploadFileToGoogleDrive(data, file, fn, date) {

    try {

    var dropbox = "OE Audit Pictures";
    var folder, folders = DriveApp.getFoldersByName(dropbox);

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


   var contentType = data.substring(5,data.indexOf(';')),
     bytes = 
       Utilities.base64Decode(data.substr(data.indexOf('base64,')+7)),

       blob=Utilities.newBlob(bytes, contentType, file)

       var dropbox2=[fn,date].join(" ");
       var folder2, folders2=folder.getFoldersByName(dropbox2)

       if (folders2.hasNext()){
           folder2=folders2.next().createFile(blob);
       } else {
          file = folder.createFolder([fn,date].join(" ")).createFile(blob);
        }
       return "OK";

       } catch (f) {
      return f.toString();
       }    
     }
1
Welcome to StackOverFlow please take this opportunity to take the tour and learn how to How to Ask and minimal reproducible example.Cooper

1 Answers

0
votes
  • In doStuff1() of "page-js.html", you want to give a value returned from getFileUrl() of "Code.gs" to userInfo.fileUrl.

If my understanding is correct, how about this modification?

Modification point:

  • google.script.run.getFileUrl() doesn't return values. When you want to use the values from getFileUrl(), you can use withSuccessHandler() as following modified script.

Modified script:

Please modify doStuff1() as follows.

function doStuff1() {
   num.picNum2 = i;
   var personName = document.getElementById("fn").value;
   google.script.run.withSuccessHandler(doStuff2).getFileUrl("fn","i"); // Modified
}

// Added
function doStuff2(fileId00) {
  var userInfo = {};
  userInfo.firstName = document.getElementById("fn").value;
  userInfo.number = i;
  userInfo.fileUrl = "https://docs.google.com/document/d/"+fileId00 +"/";
  i++;
  google.script.run.userClicked(userInfo);
}

Note:

  • In this modification, I used doStuff2() for retrieving the values from getFileUrl(). If you want to modify the function name, please modify it.

Reference:

If I misunderstood your question and this was not the result you want, I apologize.