Inserting Image into Google Sheets from Google Drive using Apps Script - google-apps-script

I have been trying for 9 days to add an image that is uploaded to my drive (via the use of a google form) into my Google sheet using Apps Script, but it isn't working and I have no idea why, this is my code below:
function getImage(){
var folderImage = DriveApp.getFolderById("0B7gxdApLS0TYfm1pRHpHSG4yTm96bm1PbTZQc1VmdGpxajY4N1J4M1gtR1BiZ0lOSl9NMjQ");
Logger.log(folderImage.getFiles().next().setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.VIEW));
Logger.log(folderImage.getFiles().next().getSharingAccess());
Logger.log(folderImage.getFiles().next().getSharingPermission());
var imageFile = folderImage.getFiles().next().getBlob();
detailSheet.insertImage(imageFile, 1, 13);
}
I have even tried making the sharing and access permissions of the to be as open as possible but I keep getting this error message:
"We're sorry, a server error occurred. Please wait a bit and try again"
I find the error message ambiguous which leads me at a dead end. Usually the message gives me a good idea of where I have gone wrong.
I believe my code is correct, and during my research I have found no definitive reason this shouldn't work. Does anybody know where I am going wrong?
A solution would be great but preferably a critique on my code so I can learn :)

Couple of issues with your script:
You never bind to a specific file, so to work with the same file you have to reinitialize the iterator each time.
You don't verify its mimetype prior to using it as an image
An example that resolves those issues:
function addFolderPNGs_(sheet, folderId) {
const folder = folderId ? DriveApp.getFolderById(folderId) : DriveApp.getRootFolder(); // scope only to the root or given folder.
const imgs = folder.getFilesByType(MimeType.PNG);
var targetRow = sheet.getLastRow();
while (imgs.hasNext()) {
var img = imgs.next();
Logger.log(img.getName())
sheet.insertImage(img.getBlob(), 1, ++targetRow);
}
}
References
getFilesByType is either folder-specific (above) or operates on all of Google Drive
DriveApp
Folder
MimeTypes
Sheet#insertImage

Related

TypeError: Cannot read property 'getBody' of null

I'm trying to teach myself to use Google Apps Script, but somehow every function I try returns this error immediately. And since I'm a huge beginner, I don't know what I'm doing wrong.
Here's a simple example of a code I tried to run:
function myFunction(){
//application
//file
var ad = DocumentApp.getActiveDocument();
var docBody = ad.getBody () ;
var paragraphs = docBody.getParagraphs();
//paragraphs[0]. setText ("MY NEW TEXT"):
//var attr = paragraphs[0].getAttributes() ;
//Logger.log(attr);
paragraphs[0].setAttributes({FONT_SIZE:40});
}
Yet no matter what I'm running really, I get this:
TypeError: Cannot read property 'getBody' of null
myFunction # Code.gs:5
What am I doing wrong?
I have an open Google Doc, I've allowed permissions to run the script project. What else should I try? Thanks.
In order to get getActiveDocument() working you need to use it in a script that is container-bound:
Create a new Google Document
Go to Extensions > Apps Script
Run your function inside of it.
If your script is not container-bound, you need to use the openById(id) or openByUrl(url) methods, in order to retrieve a Document
Adblock software was preventing the running somehow. Disabled it and runs fine now. Disregard!

my script "GET URL from google document" does not work any more - server failure WHY?

In general I want to print the URL of the google document I am actually working with in a text field.
If I copy the google sheet the function should also work for the new document.
I scripted a solution which was working for 20 month and now I have a problem.
Now I would like to know what could happen? Why do I have a server problem? Is is it possible to have to many google documents, (i have ~9000 - it works as a small ERP system) that the server got problems?
Formula in Google sheet:
=hyperlink(getSheetUrl()
Code in Script editor:
function getSheetUrl() {
var SS = SpreadsheetApp.getActiveSpreadsheet();
var ss = SS.getActiveSheet();
var url = '';
url += SS.getUrl();
url += '#gid=';
url += ss.getSheetId();
return url;
}
This is the error message in my document:
Error: Server error occurred. Please try saving the project again. (Row 0).
If I try to save the project in my script editor I get no failure.
If I try to run the project in my script editor I get:
A server error has occurred. Please try to save the project again.
Thanks for your answers.
Today I started the system and everything works fine.
Yesterday i was also able to run my code in a new enviroment, but i was not able to copy a existing document. there i got the failure.
Maybe it was really because the lan connection was to weak.
My company is a very rural area ;)
I will take an eye on that,
By the way.
Does anyone has another idea how to get the link from a document and print it in a textfield in the same document (hopefully you know what i mean)

Drive API - file or folder access timeout

I have a simple script to get files from Drive and print. When I run this it runs for about 400-500 seconds and I am getting timeout error.
I have two google accounts. Same script works in account-1(testing account) but not in account-2(main account).
Any help in isolating this issue would be more helpful.
Tried stepping through debugger the control comes back again and again to line-4 (file.hasNext()). How do I debug and make this script work?
My goal: to open specific file in the drive given a file name.
function myHelloWorld() {
Logger.log("Hello world\n");
var files = DriveApp.getFiles();
if (files.hasNext()) {
Logger.log("There are files\n");
}
}
Note:
1) Permission to run this script in both accounts were allowed (as part of first run).
2) No log messages were generated (View->Logs)
3) Timeout error was found in (View->Execution transcript)
Code works fine
#KarthikMS - there's nothing wrong with the code. It works perfectly fine from my app: it's debugging nicely - see here:
It's logging as expected
And you can also see the logs: it's running nicely too:
The code: do you want it to iterate?
I suspect that you want it to iterate through all the files? If so you need to use a while() statement and not an if statement. Then it will iterate through all the files. Something like this
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
}
Have you given this script permission to access your google drive?
You will need to authenticate the script to access your google drive. See here:
https://developers.google.com/apps-script/guides/services/authorization
I hope this helps?
It works okay:
Try it this way:
function myFiles()
{
var files = DriveApp.getFiles();
while(files.hasNext())
{
var fi=files.next();
Logger.log('FileName: %s',fi.getName());
}
}

Google Apps Script server error when trying to add an editor to a Google Document

I have some code that looks like this
var folder = DriveApp.getFolderById(/* destination folder id */);
var doc = DriveApp.getFileById(/* document file id */);
var id = doc.makeCopy(folder).setName(/* name of copy */).getId();
var new_doc = DocumentApp.openById(id);
new_doc.addEditor(/* some email address */);
Running this causes the script to stop at the last line and throw this error:
We're sorry, a server error occurred. Please wait a bit and try again.
If I comment out the line, then the script runs fine.
Also if new_doc is a File instead of a Document, then the last line works fine too. It's only when new_doc is a Document type that it gives me an error. Apparently, it doesn't work for Document types either. Although the error I get is different from when it's a File:
Cannot use this operation on a Team Drive item.
Very weird, because this was working a while ago.
All resources used in this script (the script, the destination folder, the file that is copied, the copy, etc.) are in a Team Drive.
I am puzzled as to how or why this error is happening and I am looking for help in getting around this issue.
Add the editor through the DriveApp as opposed to the DocumentApp.
It appears to be a bug with DocumentApp, SpreadsheetApp and FormApp when working with Team Drive files.
var folder = DriveApp.getFolderById(/* destination folder id */);
var doc = DriveApp.getFileById(/* document file id */);
var id = doc.makeCopy(folder).setName(/* name of copy */).getId();
var new_doc = DriveApp.getFileById(id); //updated this from DocumentApp to DriveApp.
new_doc.addEditor(/* some email address */);

Why Google Apps Script hangs on calling next() function

Today I can't run scripts connected to a specific Google Spreadsheet which contains .next() function calls, which I use to access other Spreadsheets by name. It shows Running script Cancel Dismiss message at the top of spreadsheet until exceeding maximum execution time. The strange thing is that I have similar files for every day with exactly same scripts, and the one for yesterday works fine. I created MWE below. So, when I run it I can get the alerts for the first 2 messages, but not the 3rd one.
function test_script_hanging() {
var ui = SpreadsheetApp.getUi();
ui.alert("before getting files by name");
var getFilefile = DriveApp.getFilesByName("file");
ui.alert("after getting files by name");
var getID = getFilefile.next().getId();
ui.alert("after getting Id");
}
In some situations I notice an error message saying something like "Authorization is needed to perform this action" on the line where the .next() function is being called. I tried to revoke authorization of the file and give authorization again, but that didn't help. I tried to give full access to a given script, but couldn't google the way to do it.
Maybe I can add some more functions in my script to require full access during authorization, and maybe that will help to run my main function.
My questions are:
Why the script hangs?
How to fix this?
Can such kind of things (randomly and without any notice) happen in a free version of Google account?
This works for me:
var fldr = DriveApp.getFolderById(folderID)
var file = fldr.getFilesByName(filename);
while(file.hasNext())
{
var fi = file.next();
if(fi.getName() == filename)
{
var id=fi.getId();
}
}