Google App Script ContentService downloadAsFile not working

后端 未结 1 626
难免孤独
难免孤独 2021-02-06 07:20

I have a web app developed using Google App Script HtmlService and from the html form, populating excel sheet in the Google drive using SpreadsheetApp.

1条回答
  •  悲&欢浪女
    2021-02-06 07:58

    To get downloadAsFile() method to work the contentservice object has to be returned from a doGet() or a doPost() called from the published URL.

    Example:

     function doGet(){
            var output = ContentService.createTextOutput();
            output.setMimeType(ContentService.MimeType.CSV);
            output.setContent(csvString);
            output.downloadAsFile(csvFileName);
            return output;
    }
    

    In your code you are returning the ContentService object to a webpage via google.script.run. It will not request a download from the browser. In fact returning a contentservice object will result in an error as it is not a valid object to return to a google.script.run call. Only native javascript objects are allowed.

    If you want it to work you would need to present the users with a link to click that would point to your script in another tab. Or you can use the 'download' attribute on an anchor tag pointing to your script.

    For example, and this assumes you keep the return fix to downloadDoubleQuateCsvFile():

    function doGet(e){
       var serveCSV = e.parameter.servecsv;
       if(serveCSV){return downloadDoubleQuateCsvFile()}
       return HtmlService.createTemplateFromFile('index').evaluate()
    .setTitle('Go Smart')
    .setSandboxMode(HtmlService.SandboxMode.IFRAME);
    
    }
    

    In your webpage:

    Click here to download
    

    Remeber that this is not supported in all browsers. (Think only chrome,opera,firefox supports autodownload).

    0 讨论(0)
提交回复
热议问题