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

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:

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
}

Leave a Comment