How to base64 encode a file in NativeScript

plugins
ios
nativescriptcore

#1

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!


#2

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);


#3

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


#4

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.


#5

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


#6

The code should be same for encoding any file

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

#7

thank you for your solution


#8

is there anyway to make this work on IOS ?


#9

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


#10

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


#11

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