Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download file from Google Drive to local folder from Google Apps Script

I'm trying to download a specific *.csv file from my Google Drive to a local folder on my computer. I have tried the following with no luck:

ContentService.createTextOutput().downloadAsFile(fileName);

I don't get an error, and nothing appears to happen. Any ideas on what's wrong with my attempt?

like image 391
Jason Griffin Avatar asked Jun 29 '13 02:06

Jason Griffin


1 Answers

ContentService is used to serve up text content as a Web Application. The line of code you've shown does nothing on it's own. Assuming that it's a one-line body of a doGet() function that you've deployed as a Web App, then here's why you're seeing nothing:

  • ContentService - use Content Service, and...
  • .createTextOutput() - create an empty text output object, then...
  • .downloadAsFile(fileName) - when a browser invokes our Get service, have it download the content (named fileName) rather than displaying it.

Since we have no content, there's nothing to download, so you see, well, nothing.

CSV Downloader Script

This script will get the text content of a csv file on your Google Drive, and serve it for downloading. Once you've saved a version of the script and published it as a web app, you can direct a browser to the published URL to start a download.

Depending on your browser settings, you may be able to select a specific local folder and/or change the file name. You have no control over that from the server side, where this script runs.

/**
 * This function serves content for a script deployed as a web app.
 * See https://developers.google.com/apps-script/execution_web_apps
 */
function doGet() {
  var fileName = "test.csv"
  return ContentService
            .createTextOutput()            // Create textOutput Object
            .append(getCsvFile(fileName))  // Append the text from our csv file
            .downloadAsFile(fileName);     // Have browser download, rather than display
}    

/**
 * Return the text contained in the given csv file.
 */
function getCsvFile(fileName) {
  var files = DocsList.getFiles();
  var csvFile = "No Content";

  for (var i = 0; i < files.length; i++) {
    if (files[i].getName() == fileName) {
      csvFile = files[i].getContentAsString();
      break;
    }
  }
  return csvFile
}
like image 104
Mogsdad Avatar answered Sep 17 '22 15:09

Mogsdad