Cannot add image from Google Drive to a Google Form using Apps Script

烂漫一生 提交于 2019-12-13 16:15:31

问题


I am trying to programmatically add an image from my Google Drive to a Google form. I can get it to work using a reference to a static image URL by using the google example such as:

var img = UrlFetchApp.fetch('https://www.google.com/images/srpr/logo4w.png');
form.addImageItem().setImage(img);

This works o.k. but I want to refer to an image in my Google Drive account.

If I try and use the image share link to a Google Drive image I get an error:

var img = UrlFetchApp.fetch("https://drive.google.com/open?id=0B_u2iAm1LaoZSHd1TTExcDFrbUU");
form.addImageItem().setImage(img);

ERROR: "Blob object must have an image content type for this operation."

And if I try and open the file by it's ID I get a different error:

var img = DriveApp.getFileById("0B_u2iAm1LaoZSHd1TTExcDFrbUU");
form.addImageItem(img);

ERROR: "Could not add image, please wait a minute and try again."

I can't seem to find any documentation about how I can achieve this or what I am doing wrong. I tried changing the sharing settings on the image in my Google Drive to be publicly available. And I have tried to get a static image URL to the image in the Google Drive but the only URL that seems to be available is the share URL which goes to a holding/display page for the image and not the actual image itself.


回答1:


Sorry, I think I posted the wrong code segment, so actually what I am doing is:

var img = DriveApp.getFileById("a_valid_drive_file_id_here");
var imageItem = form.addImageItem();
imageItem.setImage(img);

And getting the "Could not add image, please wait a minute and try again." error.

However, I think I have now answered my own question, the example above (getting the file by ID and calling setImage) DOES work for images stored in Google Drive, however you get the error if the image is too large. Unfortunately the API does not seem to specify any size limits and the error message is not very useful and again does not say anything about the image being too large.

So I don't know what the size limit is for images added in this way, but if anyone else has the same error, try reducing the size of the image file.




回答2:


The method addImageItem does not take a parameter. It just adds an item that will hold an image to be specified. To specify that image, call setImage, passing a blob as an argument. A blob is obtained from a File object by calling its getBlob method.

var img = DriveApp.getFileById("0B_u2iAm1LaoZSHd1TTExcDFrbUU");  
var blob = img.getBlob();
form.addImageItem().setImage(blob);

I recommend careful reading of Form and ImageItem class documentation.



来源:https://stackoverflow.com/questions/37182861/cannot-add-image-from-google-drive-to-a-google-form-using-apps-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!