0

I am trying to set up a way to upload image files into a google drive. It will create a folder using a timeid and place the image inside the folder it created. I am having trouble calling out the image file. This is how I am attempting this, the folder gets created but no image.

Please ignore any missing var for the timeid variable. This is working fine.

Error given: ReferenceError: imgInp is not defined

Thank you in advance for your help!

Code.gs

  var day = d.getDate();
  var month = d.getUTCMonth();
  var hour = d.getHours();
  var minutes = d.getMinutes();
  var realmonth = month+1;
  var timeid = String(year)+"-"+String(realmonth)+"-"+String(day)+"-"+String(hour)+"-"+String(minutes);
  var foldername=timeid;
  var parentFolder=DriveApp.getFolderById("##############");

function upload(){
  var newFolder=parentFolder.createFolder(timeid);

  var folderidlookup = newFolder.getId();

  var destination = DriveApp.getFolderById(folderidlookup);
  var imgf = imgInp;
  var contentType = 'image/jpeg';
  var imgf = imgf.getAs(contentType);
  destination.createFile(imgf)


}

Html

       <form>

        <div class="file-field input-field">

         <div class="waves-effect waves-light btn" id="wholebtn"><i class="material-icons right">cloud</i>Browse
         <input type="file" name="imgInp" id="imgInp" onchange="loadFile(event)">

        </div> 
        <div class="file-path-wrapper">
         <input type="text" class="file-path">
        </div>
        </div>
       </form>
    <button class="btn waves-effect waves-light" type="submit" name="action" id ="button">Submit
      <i class="material-icons right">send</i>
    </button>

JS

<script>
  document.getElementById("button").addEventListener("click",upload); 

  function upload(){

     google.script.run.upload();

  }
</script>
Kevin M
  • 11
  • 6

2 Answers2

1

The error you're getting is because you're trying to use a imgInp variable which you don't have it defined in any part of the code. You can get the blob file from the input, convert it to a binary array string, pass it to the server-side and finally use it to create your blob and the given Drive file, for this I used the code from this answer.

Using the examples for how to work with forms and success and failure handlers from the HTML Service guide, I put together the below code which worked successfully uploading the given image:

Index.html

<!DOCTYPE html>
<html>
<head>
    <base target="_top">
</head>
<body>
    <form>
        <div class="file-field input-field">
            <div class="waves-effect waves-light btn" id="wholebtn"><i class="material-icons right">cloud</i>Browse
                <input type="file" name="imgInp" id="imgInp">
            </div>
            <div class="file-path-wrapper">
                <input type="text" class="file-path">
            </div>
        </div>
        <button class="btn waves-effect waves-light" name="action" id="button">Submit
            <i class="material-icons right">send</i>
        </button>
    </form>
    <script>
        // Prevent forms from submitting.
        function preventFormSubmit() {
            var forms = document.querySelectorAll('form');
            for (var i = 0; i < forms.length; i++) {
                forms[i].addEventListener('submit', function(event) {
                    event.preventDefault();
                });
            }
        }

        // Add event listeners 
        window.addEventListener('load', preventFormSubmit);
        document.getElementById("button").addEventListener("click", upload);

        // Handler function
        function logger(e) {
            console.log(e)
        }

        async function upload() {
            // Get all the file data
            let file = document.querySelector('input[type=file]').files[0];

            // Get binary content, we have to wait because it returns a promise 
            let fileBuffer = await file.arrayBuffer();
            // Get the file content as binary and then convert it to string 
            const data = (new Uint8Array(fileBuffer)).toString();
            // Pass the binary array string to uploadG funciton on code.gs
            google.script.run.withFailureHandler(logger).withSuccessHandler(logger).uploadG(data);
        }
    </script>
</body>
</html>

Code.gs

function doGet() {
  return HtmlService.createHtmlOutputFromFile('Index');
}

function uploadG(imgInp){
  var parentFolder=DriveApp.getFolderById("[FOLER-ID]");
  var newFolder = parentFolder.createFolder('test webApp');
  var folderidlookup = newFolder.getId();

  var destination = DriveApp.getFolderById(folderidlookup);
  var contentType = 'image/jpeg';
  // Convert the binary array string to array and use it to create the Blob
  var blob = Utilities.newBlob(JSON.parse("[" + imgInp + "]"), contentType);
  blob = blob.getAs(contentType);
  destination.createFile(blob)

  return 'Filed uploaded!';
}
Andres Duarte
  • 3,166
  • 1
  • 7
  • 14
  • Thank you! You really helped me out here. However, the file name is keeps getting changed to null once inside the drive. How could I preserve the file name? – Kevin M Mar 13 '20 at 17:11
  • I've tried using the createFile parameter to give it a name from a variable which is the date ( I'm doing: destination.createFile(timeid,blob ) but this gives the file the name but it is not an image anymore. Any suggestion? Thank you! – Kevin M Mar 14 '20 at 00:52
  • Nevermind I used the .newblob to give it a name! Thanks for your help! – Kevin M Mar 14 '20 at 00:56
0

File Upload Dialog

Run upLoadMyDialog() from script editor to get it started. The select file and click upload.

function fileUpload(obj) {
  var d=new Date();
  var ts=Utilities.formatDate(d, Session.getScriptTimeZone(), "yyyy-MM-dd-HH-mm");
  var folder=DriveApp.getFolderById("****** Enter FolderId *******");
  var file=folder.createFile(obj.file1).setName(ts);
}

function uploadMyDialog() {
  var ss=SpreadsheetApp.getActive();
  var html='<form><input type="file" name="file1"/><br /><input type="button" value="Upload" onClick="google.script.run.fileUpload(this.parentNode);" /></form>';  
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html),"Upload File");
}

With eventListener:

function uploadMyDialog() {
  var ss=SpreadsheetApp.getActive();
  var html='<form id="f1"><input type="file" name="file1"/><br /><input type="button" value="Upload" id="btn1" /></form>'; 
  html+='<script>window.onload=function(){document.getElementById("btn1").addEventListener("click",function(){google.script.run.fileUpload(document.getElementById("f1"))})}</script>';
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html),"Upload File");
}
Cooper
  • 59,616
  • 6
  • 23
  • 54
  • Is there anyway you can do this with .addeventlistener? I am trying to use this eventlistener to run two functions on the same button once it is clicked. Thank you! – Kevin M Mar 11 '20 at 22:04