且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 Google Apps 脚本将文件从 Google Drive 下载到本地文件夹

更新时间:2023-12-04 21:19:34

ContentService 用于将文本内容作为 Web 应用程序提供.您显示的代码行本身没有任何作用.假设它是您已部署为 Web 应用程序的 doGet() 函数的单行主体,那么这就是您什么都看不到的原因:

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.

此脚本将获取您 Google 云端硬盘上 csv 文件的文本内容,并将其提供给下载.保存脚本版本并将其发布为 Web 应用程序后,您可以将浏览器定向到发布的 URL 以开始下载.

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
}