Now I'm getting File object by this line:
file = document.querySelector('#files > input[type="file"]').files[0]
I need to send this file via json in base 64. What should I do to convert it to base64 string?
Now I'm getting File object by this line:
file = document.querySelector('#files > input[type="file"]').files[0]
I need to send this file via json in base 64. What should I do to convert it to base64 string?
Building up on Dmitri Pavlutin and joshua.paling answers, here's an extended version that extracts the base64 content (removes the metadata at the beginning) and also ensures padding is done correctly.
Here are a couple functions I wrote to get a file in a json format which can be passed around easily:
JavaScript btoa() function can be used to convert data into base64 encoded string
If you're after a promise-based solution, this is @Dmitri's code adapted for that:
Try the solution using the
FileReader
class:Notice that
.files[0]
is aFile
type, which is a sublcass ofBlob
. Thus it can be used withFileReader
.See the complete working example.