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.
The flow of this sample script is as follows.
- Run
dialog()
.- Open a dialog.
- When users click a download button, retrieve file ID at GAS side.
- Create download URL from the file ID. Download URL and filename are sent to
download(obj)
of Javascript. - Create a tag for downloading and click it at Javascript side.
- By this, users can download the file of file ID.
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()
};
}
<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>
For example, when the text data is downloaded, this method can be also used. https://stackoverflow.com/q/66308153/7108653 In this method, the text data is converted to the data URL. By this, the text data is not required to be created as a file. Also, for example, when you want to make users download the image data and PDF data by downloading from the URL, this method can be also used.
Still works in 2021. Similar SO post with more generic file solution: https://stackoverflow.com/questions/20281272/initiate-a-download-from-google-apps-script/69548483#69548483