How to base64 encode a file in NativeScript



i am a newbi and my English is not good. I want to convert a file to base64 then i upload it to the server. I have done like instruction on Base64 encode audio file for the web but the endcoding is not true and i can’t open the file. please tell me about your solution. thank you!


Are you encoding audio files or images?

To encode an image, first import enums:

const enums = require("ui/enums");

then convert the image:

const imageAsBase64 = image.toBase64String(enums.ImageFormat.png);


i want endcode all type of files: png, jpg, pdf, txt …


I don’t think there is a built-in api to encode any file into Base64 string but basically it will be just a line of code. As your original question talks about audio files, here I have a demo that downloads a random mp3 file from internet and encodes it into base64 format then play same in WebView to verify it is encoded properly.


i not only want endcode audio files but also encode pdf, doc, txt …


The code should be same for encoding any file

const base64String = android.util.Base64.encodeToString(file.readSync(), 


thank you for your solution


is there anyway to make this work on IOS ?


NativeScript let you access any native api, so writing iOS version should not be a big deal.


i will appreciate it if you could give me an example, i am kinda new to nativescript


For iOS is should be file.readSync().base64EncodedStringWithOptions(0), find update Playground example below.