Estimate Attachment Size

Hi

I want to estimate the file size of an attachment, in my case a photo, before using it in a PDF. What is the best way to estimate the file size of an attachment in CloudCode?

You could try the following:
CloudCode

let buffer = await object.attachment.toBuffer(); // could also have used toArrayBuffer()
let byteLength = buffer.byteLength;
console.log(`Bytes: ${byteLength}`);

let decimalKBs = byteLength/1000;
let decimalMBs = byteLength/1000/1000;
console.log(`Size in KBs: ${decimalKBs.toFixed(0)} KB`)
console.log(`Size in MBs: ${decimalMBs.toFixed(2)} MB`)

Runtime (App)

let buffer = object.attachment.toArrayBuffer();
let byteLength = buffer.byteLength;
console.log(`Bytes: ${byteLength}`);

var decimalKBs = byteLength/1000;
var decimalMBs = byteLength/1000/1000;
console.log(`Size in KBs: ${decimalKBs.toFixed(0)} KB`)
console.log(`Size in MBs: ${decimalMBs.toFixed(2)} MB`)

The byteLength function will return the number of bytes contained in the buffer which is an accurate estimation of the size of the file.

PS. On a technical note, if you want the binary KB and MB values, instead of the decimal ones, then you would divide by 1024 instead of 1000.