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?
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With