Reputation: 665
I have built a custom menu for a spreadsheet in Google Spreadsheets. The last thing I'm trying to add is a menu item with a shortcut to the File - Import - Upload (select a file from your computer) dialog box.
I have tried using Google Picker, used the example here: https://developers.google.com/apps-script/guides/dialogs#file-open_dialogs
I have that working but Google Picker works well for selecting files from Google Drive. All I need is simply to open the File - Import - Upload (select a file from your computer) dialog from my custom menu. I thought it would be easy to do but haven't figured it out yet. How can I accomplish this?
Upvotes: 0
Views: 2300
Reputation: 17621
If you're looking for code samples on using Google Picker with Apps Script, you can use Amit Agarwal's sample here.
Here's a snippet from the tutorial:
function onOpen() {
SpreadsheetApp.getUi().createMenu('Google Picker')
.addItem('Choose Folder', 'showPicker')
.addToUi();
}
/**
* Displays an HTML-service dialog in Google Sheets that contains client-side
* JavaScript code for the Google Picker API.
*/
function showPicker() {
var html = HtmlService.createHtmlOutputFromFile('Picker.html')
.setWidth(600)
.setHeight(425)
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi().showModalDialog(html, 'Select Folder');
}
function getOAuthToken() {
DriveApp.getRootFolder();
return ScriptApp.getOAuthToken();
}
Upvotes: 0
Reputation: 5892
You can upload a file using an input Type ="file" element of HTML in your dialog box like so.
GS script:
// Your menu item must call FileUplaodDialog when clicked.
function FileUploadDialog() {
var html = HtmlService.createHtmlOutputFromFile('FileInput')
.setHeight(100)
SpreadsheetApp.getUi()
.showModalDialog(html, 'File upload dialog');
}
function uploadFile(frmdata) {
var fileBlob = frmdata.fileToUpload
if(fileBlob.getName() != "") {
var fldrSssn = DriveApp.getFolderById("Your Folder ID Here");
var picFile= fldrSssn.createFile(fileBlob);
}
}
HTML File : FileInput
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form id="fileform" onsubmit="event.preventDefault()">
<input type="file" id ="file" name="fileToUpload">
<input type="Button" value="Upload" onclick="uploadthis(this.parentNode)">
</form>
</body>
<script>
function uploadthis(frmData){
google.script.run
.withSuccessHandler(closeDialog)
.withFailureHandler(alertFailure)
.uploadFile(frmData);
}
function closeDialog(){
google.script.host.close()
}
function alertFailure(error){
google.script.host.close()
alert("failed Upload"+error.message)
}
</script>
</html>
Basically, this creates a form in the dialog box which can be used to get a fileBlob. This fileBlob is used to create a file in the drive.
Upvotes: 2