Using base64-encoded images with HtmlService in Apps Script
To get the encoded base64 string in the first place from Google Drive files:
GS
var response = UrlFetchApp.fetch('https://googledrive.com/host/fileId/name.png');
var blob = response.getBlob();
var bytes = blob.getBytes();
var base64String = Utilities.base64Encode(bytes);
Logger.log(base64String);
// now copy and paste into html
HTML
<img src="data:image/png;base64, <base64String>" alt="img name" />
This is Issue 1558 for the Google Caja compiler - visit and star it to "vote" and receive updates. Have you tried testing in the Caja Testbed?
An alternative may be to have a server-side function retrieve the base64 encoded image via UrlFetch, decode it using base64Decode, then save the blob as an image file and host it from Google Drive. I expect this would be very slow, unfortunately.
As of December 2014, Google Apps Script has added an additional IFRAME
sandbox mode, which supports data URIs (since it does not use the Caja compiler). The downside is that IFRAME
mode is not compatible with older browsers, but depending on your requirements that may not be an issue.
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);