Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an image from a Google Apps Script Web App?

I am trying to make a Web App with Google Apps Script that actually returns an image file instead of just text. I tried it as simple as that:

function doGet() {
    var file = DriveApp.getFileById('[redacted]');
    return file;
}

When publishing it as a web app and executing it, it just says

The script completed but did not return anything.

I know the file exists and is accessible, since I can print its MIME type, which is a proper image/png. So I'm missing something obvious here, but being not particularly well-versed in Google Apps Script, let alone web development of any kind, I don't know what that is I'm missing and searching for introductory material on returning an image from a Google Apps Script has not been particularly fruitful either, especially when I'm not realyl sure where to start at all.

Is it even possible to return an image file from a web app via Google Apps Script?

like image 841
Christian Rau Avatar asked Apr 18 '16 16:04

Christian Rau


1 Answers

doGet() is a reserved function name. The function name is reserved for listening to a GET request made to the published URL of the Web App. The GET request that is made to the published URL of the Web App is the "event" and the doGet() function is triggered by the event.

The doGet() function can return two different types of output.

  • HTML Output Object - HtmlService
  • Text Output Object - ContentService

The most common use of doGet() is to return HTML content to the browser. But using HtmlService to return file content won't work.

doGet() can also be used together with "Content Service" to return text content in various forms.

The text content can be returned as plain text, or the MIME Type of the text content can be set before returning it. The MIME type can be:

  • ATOM
  • CSV
  • ICAL
  • JAVASCRIPT
  • JSON
  • RSS
  • TEXT
  • VCARD
  • XML

But there is no MIME Type setting to return file types.

If the file can be converted to text content, returned, and then formatted in the browser, then that is a possibility. If you want to return something like an image file, then you would need to convert the image to a Blob, then get the blob as a string, and then return the string.

like image 188
Alan Wells Avatar answered Oct 29 '22 08:10

Alan Wells