Skip to content

Instantly share code, notes, and snippets.

@murillodutt
Forked from tanaikech/submit.md
Created January 14, 2021 20:20
Show Gist options
  • Save murillodutt/6d4126ec4e3bf6f95e9fe6a12e50f201 to your computer and use it in GitHub Desktop.
Save murillodutt/6d4126ec4e3bf6f95e9fe6a12e50f201 to your computer and use it in GitHub Desktop.
Downloading File Using Button of Dialog Box on Google Docs

Downloading File Using Button of Dialog Box on Google Docs

This is a sample script for downloading a file using a button of dialog box on Google Docs (Spreadsheet, Document and Slides).

Please use this sample script at script editor on Google Docs (Spreadsheet, Document and Slides). And please set file ID in the script.

FLow :

The flow of this sample script is as follows.

  1. Run dialog().
    • Open a dialog.
  2. When users click a download button, retrieve file ID at GAS side.
  3. Create download URL from the file ID. Download URL and filename are sent to download(obj) of Javascript.
  4. Create a tag for downloading and click it at Javascript side.
  • By this, users can download the file of file ID.

Code.gs

function dialog() {
  var html = HtmlService.createHtmlOutputFromFile('download');
  SpreadsheetApp.getUi().showModalDialog(html, 'Sample dialog'); // If you use other Google Docs, please modify here.
}

function getDownloadUrl() {
  var id = "### file id ###";

  var file = DriveApp.getFileById(id);
  return {
    url: file.getDownloadUrl().replace("?e=download&gd=true",""),
    filename: file.getName()
  };
}

download.html

<input type="button" value="download" onclick="getUrl()" />
<script>
  function getUrl() {
    google.script.run.withSuccessHandler(download).getDownloadUrl();
  }

  function download(obj) {
    var d = document.createElement('a');
    d.href = obj.url;
    d.download = obj.filename;
    d.click();
  }
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment