venubty
venubty

Reputation: 11

Upload file with google apps script using html service

I want to upload a file using the HtmlService of GAS but it doesn't work. I found informations in this topic Uploading file using Google Apps Script using HtmlService but it doesn't fit with my issue. Here is an example that describes my problem:

Code.gs:

    function doGet() {

    return HtmlService.createTemplateFromFile("index").evaluate();

    }

    //For some reasons, this function has to be in code.gs
    funcion getHTML() {

        var html = "<form id='myform'>"+
                     "<input name='myfile'>"+
                   "</form>"+
                   "<div data-formname='myform'> Submit form </div>";

    return html;

    }

    function uploadFile(file) {

      DriveApp.createFile(file); *//Doesn't work :/*

    }

Javascript:

    $(document).on("click","div", function(e) {

    var idform = $(this).data("formname");

    if (idform) 
    sendForm(idform);


    });

function trigger() {

google.script.run.withsuccesshandler(setHTML).getHTML();

}

function setHTML(html) {

$("#myHTML").html(html);

}

function sendForm(idForm) {

var formElements = document.getElementById("idForm").elements;
var form = {};

for (var key in formElements) form[key] = formElements[key];

google.script.run.withsuccesshandler().uploadFile(form["myfile"]);

}

index.html

<body onload="trigger()">

<div id='myHTML'></div>

</body>

Upvotes: 1

Views: 2282

Answers (1)

Serge insas
Serge insas

Reputation: 46822

Your code seems a bit overcomplicated... try this simple code

code.gs

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

function serverFunc(theForm) {
   var fileBlob = theForm.theFile;         // This is a Blob.
   var adoc = DocsList.createFile(fileBlob);    
   return adoc.getUrl();
}

index.html

<div>
<script>
function cliHandler(e){
  document.getElementById('button').value = "Document is downloadable at url "+e  
  }
</script> 

<form>
   <input type="file" name="theFile">
   <input type="button"  value="UpLoad" id="button" onclick="google.script.run.withSuccessHandler(cliHandler).serverFunc(this.parentNode)">
</form>
</div>

Upvotes: 2

Related Questions