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.
- 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.
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>