How to Save Base64 Data to a File

Description

Base64 encoded data can be converted back to its original format and saved as a file.

Discussion

Apps can capture and save data, such as images, as base64 encoded information, which can then be embedded directly in the HTML generated for an application instead of downloading a separate image file to the device. You can convert base64 encoded information back to its original file format and save it to disk using the base64Decode() Xbasic function. The resulting data can then be saved to storage -- such as AmazonS3 or the server file system.

For example, here's the base64 encoded data for a red dot:

dim img64 as c = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="

The data, stored in the variable img64, can be decoded to a blob containing the PNG image data:

dim decodedImg as b
decodedImg = base64decode(img64)

Finally, the blob can be saved as a .png file in storage:

dim filename as c = "mydata.png"
dim mime as c = "image/png"
dim result as P
a5storage_savedata("::storage::disk",decodedImg,filename,mime,result)

? result
= AbsolutePath = "file://C:\Users\user1\Documents\AlphaAnywhere\Demo\Demo.WebProjects\Default.WebProject\images\mydata.png"
ContentType = "image/x-png"
hasError = .F.
ModifiedTime = 05/06/2021 12:29:25 64 pm
Name = "mydata.png"
size = 85
timeTakenMilliseconds = 5

You may need to specify the mime type for your file format when uploading the file to storage. See Media types for a list of mime types.

See Also