This blog will discuss how to calculate the size of a media file in a canvas app. This can be useful if needed to do some validation on the size of the media that will be uploaded by a user. The demo below shows the scenario where the app displays the size of an image as a notification when a user has uploaded it from his device.
How it works ?
The Add picture control is used to load the picture from the user’s device. In fact, this control is a group of two controls. The sub-control we are interested in is “AddMediaButton“. Indeed, it contains the onChange property which will allow us to display the notification when the file is loaded.
The idea to calculate the file size is to encode it in base64. Then use the following formula to estimate its size. This formula is taken from the base64 encoding specifications. You can refer to the following Wikipedia page for more details.
bytes = (string_length(encoded_string) - 814) / 1.37
The file encoding is possible thanks to the JSON function by specifying the IncludeBinaryData option.
Then, it would be possible to estimate the size of the file using the formula listed above. This is expressed in the following code. Adding the division by 1000 gives the result in KO.
To display everything as a notification, the following code is used:
Notify("Size : "& RoundUp(((Len(JSON(UploadedImage1.Image,JSONFormat.IncludeBinaryData))-814)/1.37)/1000,0) & " KO");
Hope it helps …