2

I am trying to get a png image in google drive to appear on a google apps script html page. I can get the image to appear on the script html page if it is just at a URL somewhere on the web (see commented out line below), but not from google drive. Here is part of the code where I am trying to get as a blob and then use it in an image tag:

function getImage() {
//The next 2 lines don't produce the image on the page
  var image = DriveApp.getFileById('File Id Goes Here').getBlob().getAs('image/png');
  var image = '<img src = "' + image + '" width = "90%">'
  //Note, the next line uncommented produces an image on the page
//var image = '<img src = "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" width = "90%">'
return image
}

function doGet() {
  var htmlToAppend = getImage(); 
   var html = HtmlService.createTemplateFromFile('index').evaluate()
              .setTitle('Google Image').append(htmlToAppend).setSandboxMode(HtmlService.SandboxMode.IFRAME);  
  return html;    
}

The result is a missing image on the html page produced by the script, with the URL for the missing image ending in script.googleusercontent.com/Blob

Info on Blob is here: https://developers.google.com/apps-script/reference/base/blob (open in a separate page/tab)

Any help is appreciated.

Mark1010
  • 21
  • 1
  • 5

1 Answers1

0

If you can see the Using base64-encoded images with HtmlService in Apps Script or Displaying files (e.g. images) stored in Google Drive on a website, there are some workaround to get the image from drive.

One workaround is using the IFRAME sandbox mode, but this doesn't support old browsers.

All that's required is to call setSandboxMode() on your template, and your data URIs should work as expected:

var output = HtmlService.createHtmlOutput(
'<img src="data:' + contentType + ';base64,' + encoded + '"/>'
);

output.setSandboxMode(HtmlService.SandboxMode.IFRAME);

The second is using the permalink of the file:

https://drive.google.com/uc?export=view&id={fileId}

But be noted that Serving images in an Apps Script through HtmlService is deprecated .

<img src="https://googledrive.com/host/0B12wKjuEcjeiySkhPUTBsbW5j387M/my_image.png" height="95%" width="95%">

Also, refrain from using same variable names to avoid error from occuring

Hope this helps.

Community
  • 1
  • 1
Mr.Rebot
  • 6,703
  • 2
  • 16
  • 91