I try to upload file to my 'mysitename' Google Site. I using this script, but it does not work
function doGet(e) {
var app = UiApp.createApplication().setTitle("Upload");
var formContent = app.createVerticalPanel();
formContent.add(app.createFileUpload().setName('thefile'));
formContent.add(app.createSubmitButton());
var form = app.createFormPanel();
form.add(formContent);
app.add(form);
return app;
}
function doPost(e) {
try{
var fileBlob = e.parameter.thefile;
var pages = SitesApp.getSite('site', 'mysitename').getChildren();
var attachments = pages[0].getAttachments();
attachments[0].setFrom(fileBlob);
}catch(e){
Logger.log(e.message);
}
}
I catch error "Cannot call method "setFrom" of undefined" last modal window "Error encountered: An unexpected error occurred"
It's works! But i do not know, how to use this circular from documentation "Sets the data, content type, and name of this attachment from a Blob. Throws an exception for web attachments." What is mean this "Throws an exception for web attachments"? I'll be forced to use "try-catch-exception"
Pls, help me to do it!
I think the error is in the line
var pages = SitesApp.getSite('sites', 'mysitename').getChildren();
The documentation says
method getSite(domain, name)
Gets the site with the given domain and name.
Use "site" as the domain for consumer sites.
So, if you are within a domain, use the name of your domain, otherwise use 'site' instead of 'sites'
Related
Recently some of my app scripts are showing errors when executed simultaneously. Everything worked fine for years, apparently the change happened on Google side.
This is the execution transcript result:
Unfortunately, the error does not show file name and line number to debug it properly, but my first line is:
var ss = SpreadsheetApp.getActiveSpreadsheet()
Therefore I assume that calling SpreadsheetApp simultaneously by instances of the app is causing the error. SpreadsheetApp is not in the loop, nor inside any function. It is called to define global variable ss to be used by the app.
My apps are executed under my user name, since users should not have access to the Spreadsheet I'm accessing. I'm afraid I can't keep the entire Spreadsheet in Cache Service - I want app to update the Spreadsheet when it it called.
UPDATE:
Here is some relevant code from one of the apps.
function doGet(e){
var ref = e.parameter.ref;
var ss = SpreadsheetApp.openById('########')
var logsheet = ss.getSheetByName('LOG');
logsheet.appendRow([new Date(),ref,JSON.stringify(e.parameter)])
try{
//Main code goes here
return ContentService.createTextOutput(JSON.stringify({result:"ok"})).setMimeType(ContentService.MimeType.JSON);
}catch(e){
return ContentService.createTextOutput(JSON.stringify(e)).setMimeType(ContentService.MimeType.JSON)}
}
As you can see I have try {} catch(e) in my function, and since the error I'm getting is not caught by it, I assume it happens right before.
Just discovered manual hack to avoid this error:
Open your spreadsheet from private browser mode. This will increase number of document viewers and will increase limits :)
You can put everything in the try-catch block. Also remember to publish a new version of the web app before execution.
function doGet(e) {
var response = {};
try {
SpreadsheetApp.openById('########')
.getSheetByName('LOG')
.appendRow([new Date(), e.parameter.ref, JSON.stringify(e.parameter)]);
response.result = "OK";
} catch (error) {
response.result = "Error: " + error.toString();
}
return ContentService
.createTextOutput(JSON.stringify(response))
.setMimeType(ContentService.MimeType.JSON);
}
function checkACBalance() {
try{
var url ="http://sms.mydomain.com/api/balance.php";
alert(url);
var payload = {authkey:'d5558466554f11aa909d565ede677d40', route:'1'};
alert(payload);
var payload_json = encodeURIComponent(JSON.stringify(payload));
alert(payload_json);
var options = {method:"POST",contentType:"application/json",payload:payload_json,muteHttpExceptions:true};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
alert(response)
var res_code = result.getResponseCode();
alert(res_code)
}catch(e){
alert(e)
}
}
Now the problem is that when I am using this URLFetch Class for calling external API then this is not working.
In browser console an error has been shown:
Uncaught TypeError: Cannot read property 'fetch' of undefined
To build on what Kriggs is saying in the comments, it looks like you're trying to use UrlFetchApp.fetch in your .js file (the client). You want to make this call in your .gs file (the server).
Is there a way to use file upload class and mailApp to select a (pdf) file from your computer (like this tutorial shows) and stores it only temporarily (maybe using cache memory) to send it as an email attachment?
the sample you refer to needs very few modifications to do what you want... the variable you get in the doPost is a blob, the argument needed in the attachment is a blob too so it is quite straightforward to put both together.
I only added a text on the button and a confirmation message when the mail is sent.
note that the file type will depend only on the filetype of the file, nowhere we convert it to pdf but that was not the point of your question.
if you upload a jpeg (for example) it will be a jpeg in the attachment of course !
code below with test on line:
function doGet(e) {
var app = UiApp.createApplication().setTitle("Upload CSV to Sheet");
var formContent = app.createVerticalPanel();
formContent.add(app.createFileUpload().setName('thefile'));
formContent.add(app.createSubmitButton('send'));
var form = app.createFormPanel();
form.add(formContent);
app.add(form);
return app;
}
function doPost(e) {
// data returned is a blob for FileUpload widget
var fileBlob = e.parameter.thefile;
MailApp.sendEmail(Session.getActiveUser(),'test pdf attachment','see attachment',{attachments: [fileBlob]});
var app = UiApp.getActiveApplication();
return app.add(app.createLabel('mail sent'));
}
test (asking for authorization)
var spreadsheetFile = DriveApp.getFileById(sheetId);
var blob = spreadsheetFile.getAs('application/pdf');
//if daysleft =1 or 0 then send mail .
MailApp.sendEmail(emailAddress, subject, message, {
name: 'Welcome mail- Perch Arbor Golf Course.pdf',
attachments: [blob]
});
Does anybody know if there is a new limit for attaching files in a Google Site page with aps script ?
A simple example doesn't work anymore for large files :
Steps to reproduce :
1.Create a UiApp with the code below
2.Run the script in a Google Site
3.Select a small file (<1MB)
4. Result is ok, file attached.
5. Run again with a larger file (>2.6MB),
6. Result is NOK :"error encountered : an unexprected error occurred"
Source code :
function doGet(e) {
var app = UiApp.createApplication().setTitle("Upload File to Site");
var formContent = app.createVerticalPanel();
formContent.add(app.createFileUpload().setName('thefile'));
formContent.add(app.createSubmitButton("Click to upload"));
var form = app.createFormPanel();
form.add(formContent);
app.add(form);
return app;
}
function doPost(e) {
// data returned is a blob for FileUpload widget
var fileBlob = e.parameter.thefile;
SitesApp.getActivePage().addHostedAttachment(fileBlob);
}
This worked before, not since a few weeks.
This was is a known change in behavior and the team is working on resolving this.
Here is the Issue Tracker item to check -
https://code.google.com/p/google-apps-script-issues/issues/detail?id=2723
I have a script that first presents a UI containing just a button to the user. Upon clicking that button, the script goes through their documents and changes the ownership of some of the files.
Upon loading my script, the user is greeted with the standard "Authorization Required" page with the red border. The user clicks the button to grant my app the needed permissions, and is taken to the page with the button.
However, after clicking the button, the user gets a dialog that says:
Error Encountered: Authorization is required to perform that action.
The app is set to execute as the user executing the script, and the script access is set to "anyone."
Any thoughts on what might be wrong?
My doGet():
function doGet(e) {
var app = UiApp.createApplication();
var button = app.createButton('Transfer');
app.add(button);
var handler = app.createServerHandler('init');
button.addClickHandler(handler);
return app;
}
The init() method goes through a specific folder (statically set by it's ID in the script), looks for files owned by the current user, and transfers the ownership to another user.
function init() {
// Create new log as a a Drive document
var log = DocsList.createFile("Ownership Transfer Log");
var user = Session.getActiveUser();
var targetEmail = "newemail#example.com";
transferFolderOwnership('[Drive folder ID]', user.getEmail(), targetEmail, log);
}
And transferFolderOwnership:
function transferFolderOwnership(folderId, userEmail, targetEmail, log) {
var rootFolder = DocsList.getFolderById(folderId);
var files = rootFolder.getFiles();
// Transfer files
var file;
for (var i = 0; i < files.length; i++) {
file = DriveApp.getFileById(files[i].getId());
if (file.getOwner() == userEmail) {
file.transferOwnership(targetEmail);
}
}
// Do the same for folders
}
The library you are using need an authorization that can only be granted when called from the script editor (see end of the library source code : function googleOAuth_()) . The first authorization you see is only for the "local" part of you script, the other looks like this :
This is a known issue and has a possible workaround described in one of the last issue tracker posts. I didn't try it yet but I guess it could be a way to go...