google-apps-script Google Web App Script To Auto Download From Google Drive code.gs


Example

function doGet(e){
   var serveFile = e.parameter.servefile;
   var id = e.parameter.id;
   
   if(serveFile)
   {
     return downloadFile(id); // and Hyde
   }
   
  return HtmlService.createHtmlOutputFromFile('form.html'); // Jekyll
}

function fetchFromGoogleDrive() { // Jekyll
  var fileslist = DriveApp.searchFiles("your search criteria goes here + and trashed = false"); // the 'and trashed = false' prevents the same file being download more than once
  
  if (fileslist.hasNext()) {
    var afile = fileslist.next();
    var html = ScriptApp.getService().getUrl()+"?servefile=true&id="+afile.getId();
    return html;
  }
  else
  {
    return '';
  }
}
   
function downloadFile(id){ // and Hyde  
  try
  {
    var afile = DriveApp.getFileById(id);
  
    var aname = afile.getName();
    var acontent = afile.getAs('text/plain').getDataAsString();
    
    var output = ContentService.createTextOutput();
    output.setMimeType(ContentService.MimeType.CSV);
    output.setContent(acontent);
    output.downloadAsFile(aname);
    afile.setTrashed(true);
    return output;
  }
  catch (e) {
    return ContentService.createTextOutput('Nothing To Download')
  }
}