Uploading to a designated folder using Google Script

Looking to create a form for uploading files, photos, and videos to specific folders in Google Drive using Google Apps Script. However, encountering an error "invalid argument listener".

Here is the HTML index:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <title>Upload Files</title>
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b5954544f484f495a4b7b0e1509150b">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
  </head> 
  <body>
    <h1>File Uploader</h1>
    <div id="form" style="text-align:center;display:block">
    <form>
        <input class="form-control" type="file" name="myFile" mulitple>
        <br>
        <br>
        <div>
          <h3>Choose Folder to upload</h3>
          <h6>Max. 50MB</h6>
          <input class="btn btn-outline-secondary" type="button" id="submitBtn1" value="File">
          <input class="btn btn-outline-secondary" type="button" id="submitBtn2" value="Foto">
          <input class="btn btn-outline-secondary" type="button" id="submitBtn3" value="Video">
        </div>  
        <label id="resp"></label>
    </form>
    </div>
    <script>
      document.getElementById('submitBtn1').addEventListener('click',
        function(e){
          google.script.run.withSuccessHandler(onSuccess).uploadFiles(this.childNode)
        })

        function onSuccess(data_files){
          document.getElementById('resp').innerHTML = "File Uploaded successful";
        }

      document.getElementById('submitBtn2').addEventListener('click',
        function(e){
          google.script.run.withSuccessHandler(onSuccess).uploadPhotos(this.childNode)
        })

        function onSuccess(data_photos){
          document.getElementById('resp').innerHTML = "Photo Uploaded successful";
        }

      document.getElementById('submitBtn3').addEventListener('click',
        function(e){
          google.script.run.withSuccessHandler(onSuccess).uploadVideos(this.childNode)
        })

        function onSuccess(data_videos){
          document.getElementById('resp').innerHTML = "Video Uploaded successful";
        }
    </script>
  </body>
</html>

And here is the code.gs file:

function doGet() {
  var html = HtmlService.createHtmlOutputFromFile('index');
  return html.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}


function uploadFiles(data_files)
{
 var file = data_files.myFile;
 var folder = DriveApp.getFolderById('12gKxEtiZhL0hKU6qd-ngVih1DhP_UV8_');
 var createFile = folder.createFile(file);
 return createFile.getUrl();
}

function uploadPhotos(data_photos)
{
 var file = data_photos.myFile;
 var folder = DriveApp.getFolderById('1LngD6Ziqqd2i5mt-IGX3NWzVPMIAJEWU');
 var createFile = folder.createFile(file);
 return createFile.getUrl();
}

function uploadVideos(data_videos)
{
 var file = data_videos.myFile;
 var folder = DriveApp.getFolderById('1LJgcCAn1_Kb6SVVLfxzKkmiw_hg47zoP');
 var createFile = folder.createFile(file);
 return createFile.getUrl();
}

If the method If Else is required, kindly advise on how to incorporate it, as I am still learning about coding.

Answer №1

I haven't delved deep into your code review, but there seems to be an issue with the parameter in the google.run.script statements. this.childNode is currently returning undefined.

To send the "form data" to the server-side code, you need to replace it with the form node. Simply add the following code snippet within the <script> tag, before the functions:

const form = document.querySelector('form');

Then, substitute this.childNode in the script.google.run statements with the following:

google.script.run.withSuccessHandler(onSuccess).uploadFiles(form)

When I mention "form data," I mean that you have to pass the form element as the parameter to the server-side function. The aforementioned code assigns the form element (<form>...</form>) to the form variable. google.script.run will utilize the FormData interface to construct an object with properties for each form data entry element (<input>, <select>, etc.) using their name attributes as the property names and their respective element values as the property values.

Related

  • Error when <input type="file"> is blank on a submitted form (Google App Script)
  • Uploading Multiple Files to Google Drive with Google App Script

Resources

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mastering Protractor's end-to-end control flow and managing time outs

When testing an angular app using protractor, I encountered a strange issue recently. Every now and then, or since a recent update, protractor seems to stall or slow down significantly. After investigating the problem, I discovered that a simple someEleme ...

Poorly formatted mui table representation

I have utilized the Table component from @mui/material and referenced the documentation at https://mui.com/material-ui/react-table/. To reproduce the issue, I have created a static table with fixed values. Here is the code snippet: <TableCo ...

Use a dropdown menu to update the selected value

Issue with displaying drop down values in the second list, despite trying various solutions. When a user selects a country, the corresponding state should be populated from the database into the second drop-down. Any assistance would be greatly appreciated ...

Creating a range using v-for directive in Vue

For example: range(3, 5) -> [3, 4] range(5, 10) -> [5, 6, 7, 8, 9] I am aware that we can generate range(1, x) using v-for, so I decided to experiment with it like this: // To achieve the numbers in range(5, 10), I set (10 - 5) on `v-for` // and t ...

Tips for Sending an Ajax POST Request

I've been using the following code snippet to initiate a POST request to my node API in order to generate a PDF. However, upon execution, my node console displays the following errors: $('#renderPDF').click(function(){ var request = $ ...

(basic) Issue with Jquery ajax request not receiving data

The alert box is not displaying anything and is not returning any data from the specified URL, even though it should show the Google page! Any suggestions? I am using the POST method because I need to send querystring data as well. $.ajax({ ...

Problem with exporting default class in Babel/Jest conflict

Currently, I am facing a challenge while testing the code using jest. The issue seems to be related to babel, especially regarding the export of a default class. Here is an example of the code causing the problem... export default class Test { get() { ...

Spontaneously generating visuals that lead an unpredictable existence

Every 0-2 seconds, I generate a unique image and place it randomly within a designated area. setTimeout("addImage()", Math.floor((Math.random() * 2000) + 1)); To maintain order, I want these images to vanish after being visible for an interval o ...

The pause button will still function, even if the scrolling feature is enabled

I've successfully implemented a feature that pauses and plays the video on scroll when it reaches a certain pixel height. However, I'm facing an issue where the code automatically plays the video whenever the scroll position is more than 13500px ...

When troubleshooting AJAX in Chrome, only the library lines are displayed in the call stack

While using "XHR breakpoints" to identify which line is triggering an AJAX request, I noticed that the call stack only shows Angular.js library lines. This makes it difficult to pinpoint the exact line in my code that triggered the request. What steps shou ...

The instance does not have a definition for the property or method "foo" that was referenced during rendering

[Vue warn]: Property or method "modelInfo" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. Whenever I ...

Tips on displaying a confirmation box when the page is refreshed or closed

I need to implement a confirmation box for users who try to close the window without saving the content of a textarea within a form. Here is the code I currently have: var myEvent = window.attachEvent || window.addEventListener; var chkevent = window.att ...

How can I implement Before() and After() hooks within a hooks.js file for a Selenium and JavaScript project?

Within my Selenium JS / Cucumber framework, I have incorporated Before() & After() functions to handle the setup and tear down of my webdriver. To manage these functions, I decided to organize them in my customSteps.js file alongside other cucumber st ...

"Optimize Your Data with PrimeNG's Table Filtering Feature

I'm currently working on implementing a filter table using PrimeNG, but I'm facing an issue with the JSON structure I receive, which has multiple nested levels. Here's an example: { "id": "123", "category": "nice", "place": { "ran ...

compress a website to display advertisement

Here is a JSFiddle link I would like to share with you: I am currently working on squeezing the webpage to display an ad on the right side. http://jsfiddle.net/5o6ghf9d/1/ It works well on desktop browsers, but I am facing issues with iPad Safari/Chrome ...

Transforming JSON date format to a different one using Jackson libraries

My spring boot 1.3.5 application is using jackson with the dependency "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.5.0". Encountering an issue when a user inputs a date value in a format different than expected (mm/dd/yyyy) during a POST requ ...

[Vue alert]: Issue with rendering: "Sorry, unable to read property 'correct_answer' as it is undefined"

My code fetches data from an API. The questions display correctly, but the answers cause an error that crashes the app. Initially, the code worked fine in App.vue, but moving it to a different view page caused the crash. Any suggestions on how to fix this ...

Apply criteria to an array based on multiple attribute conditions

Given an array containing parent-child relationships and their corresponding expenses, the task is to filter the list based on parents that have a mix of positive and negative expenses across their children. Parents with only positive or negative child exp ...

Angular2 - HTML not displaying the response

I am currently mastering angularjs2. In my latest project, I attempted to fetch data from an API and received a response successfully. However, I encountered an issue where the response is not rendering in homepage.component.html as expected. I am unsure o ...

Exploring Array Iteration and Incrementing with Easing Techniques

I am currently working on a function that involves iterating over an array and incrementing the values by varying amounts. The challenge is to decrease these incremental amounts as the values in the array get larger. Let's consider the following exam ...