Continuing the theme of using Google Apps Script Content service and scriptDB for lots of things, today’s post cover a few tricky topics.
- How to convert an image to a blob so it can be stored in scriptDB.
- How to use the content service as a server so that we can serve up that image to some request
- How to respond to a jSonP request from Google Content service to get over cross domain request problems
- How to convert that back into an image in jQuery
function blob() { var googleLogoBlob = UrlFetchApp.fetch ("http://www.google.com/intl/en_com/images/srpr/logo3w.png") .getBlob().setName("googleLogoBlob"); var silo = mcpher.scriptDbSilo("blobs",ScriptDb.getMyDb()); silo.save ( {name: googleLogoBlob.getName(), blob: Utilities.base64Encode(googleLogoBlob.getBytes()) } ); }
Here we fetch some image, name it ‘googleLogoBlob’, convert it to base64 and save as a blob in a scriptDB silo called ‘blobs’.
function doGet(e) { return ContentService .createTextOutput(blobGet(e)) .setMimeType(ContentService.MimeType.JSON); }
The result of that is shared here, and the function that does the work , takes the name parameter, and callback parameter to handle jSonP requests.
function blobGet(e) { // imgs are in base64 format in scriptDB var stuffSilo = mcpher.scriptDbSilo("blobs",ScriptDb.getMyDb()); var results = stuffSilo.query( {name : e.parameter.name}); // find it? var result= results.hasNext() ? results.next() : { error: "no such blob " + e.parameter.name}; var j = Utilities.jsonStringify(result); // using jsonP? if (e.parameter.callback) { j = e.parameter.callback + "(" + j + ")" } return j; }
Note that if callback is specified (and it should be), the jSon response is wrapped up in a call to the given callback function.
<div id='blobs'><img id='blobsimage' src=''/></div>