- Download and upload a file
- Zip and unzip a file
- Parse a csv file
- Format a string
- base64 encode and decode a string
- Get date in the past
Download and upload a file
function sendHttpPost() { // Download a file now (GET), so we can upload it in the HTTP POST below. var response = UrlFetchApp.fetch('https://www.google.com/favicon.ico'); var fileBlob = response.getBlob(); var payload = { 'fieldOne' : 'value for field one', 'fieldTwo' : 'value for field two', 'fileAttachment': fileBlob }; // Because payload is a JavaScript object, it will be interpreted as // an HTML form. (We do not need to specify contentType; it will // automatically default to either 'application/x-www-form-urlencoded' // or 'multipart/form-data') var options = { 'method' : 'post', 'payload' : payload }; UrlFetchApp.fetch('http://example.com/upload_form.cgi', options); }
Zip and unzip a file
function zipUnzip() { var googleFavIconUrl = 'https://www.google.com/favicon.ico'; var googleLogoUrl = 'https://www.google.com/images/srpr/logo3w.png'; // Fetch the Google favicon.ico file and get the Blob data. var faviconBlob = UrlFetchApp.fetch(googleFavIconUrl).getBlob(); var logoBlob = UrlFetchApp.fetch(googleLogoUrl).getBlob(); // zip now references a blob containing an archive of both faviconBlob and // logoBlob. var zip = Utilities.zip([faviconBlob, logoBlob], 'google_images.zip'); // This will now unzip the blobs. var files = Utilities.unzip(zip); }
Parse a csv file
function parseCsv() { // This will create a 2 dimensional array of the format // [[a, b, c], [d, e, f]] var csvString = 'a,b,c\nd,e,f'; var data = Utilities.parseCsv(csvString); Logger.log(data); }
Format a string
function formatString() { // You can use sprintf-like string formatting using '%'-style format // strings. // will be: '123.456000' Utilities.formatString('%11.6f', 123.456); // will be: ' abc' Utilities.formatString('%6s', 'abc'); }
base64 encode and decode a string
function base64Encoding() { // base64 encoding is used to encode binary data to a text format // you may need to do this if your transfer method can't handle spaces, // non-English characters, etc. // We'll instantiate a blob here for clarity. var blob = Utilities.newBlob('A string here'); // Let's return the blob data as a byte[]. var encoded = Utilities.base64Encode(blob.getBytes()); // This will log 'QSBzdHJpbmcgaGVyZQ==' Logger.log(encoded); var decoded = Utilities.base64Decode(encoded); // This will log the original string. Logger.log(Utilities.newBlob(decoded).getDataAsString()); }
Get date in the past
function getDateInThePast() { var numDays = 3; var today = new Date(); today.setDate(today.getDate() - numDays); return Utilities.formatDate(today, 'PST', 'yyyyMMdd'); }