I am trying to upload and save an image from Data URI in Google Apps Script. Everything works apart from the file type being set.

I've tried all variations of newBlob as per the Apps Script documentation.

function doUpload(dataURI) {

var folder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxxxxxx");
var type = (dataURI.split(";")[0]).replace('data:','');
var imageUpload = Utilities.base64Decode(dataURI.split(",")[1]);
var blob = Utilities.newBlob(imageUpload, type, "nameOfImage");

return true;

1 Answers

Cooper On

Converting and Saving Images as DataURI's

I get the images from a url using UrlFetch. If you don't have a place to host them then just put them in Google Photo Library and copy the url from there it works too. That way you can do all your image process for web ready artwork before you convert them with standard image editors.

function convImageUrl(url){
  var url=url || "http://jimesteban.com/images/mimincoopers.png";
  var blob=UrlFetchApp.fetch(url).getBlob();
  var b64Url='data:' + blob.getContentType() + ';base64,' + Utilities.base64Encode(blob.getBytes());
  return b64Url;

function saveDataURIInFile(filename,datauri,type) {
  Logger.log('filename: %s\ndatauri: %s\ntype: %s\n',filename,datauri,type);
  if(filename && datauri && type) {
    var folder=DriveApp.getFolderById(getGlobal('MediaFolderId'));
    var files=folder.getFilesByName(filename);
    while(files.hasNext()) {
    var f=folder.createFile(filename,datauri,MimeType.PLAIN_TEXT);
    return {name:f.getName(),id:f.getId(),type:type,uri:DriveApp.getFileById(f.getId()).getBlob().getDataAsString()};
    throw('Invalid input in saveDataURIInFile.');