Skip to content Skip to sidebar Skip to footer

Calling Image File On Google App Scripts To Upload Into GoogleDrive

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

Solution 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!';
}

Solution 2:

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");
}

Post a Comment for "Calling Image File On Google App Scripts To Upload Into GoogleDrive"