1

I am working on an application in react that uses an api and to make a post we have to send an image in base64 . I was looking on stack overflow and saw this example:

function getBase64(file) {
   var reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = function () {
     console.log(reader.result);
   };
   reader.onerror = function (error) {
     console.log('Error: ', error);
   };
}

var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file); // prints the base64 string

I'm confused to why I'd use new FileReader() when I could simply have one line of code that converts the string to base 64 using btoa()? Thank you in advance!

I can make this work either way I just don't know the point of using new FileReader() vs btoa.

Elise J
  • 11
  • 1
  • You still need to read the file, preferably an async operation, so it’s not clear what you think you’d be saving by using `btoa`, although they’re not identical in functionality. – Dave Newton Aug 26 '23 at 21:30
  • less api calls. btoa requires reading the file into heap first, to then base64 it. the filereader approach will basically read it to memory in base64 format, thus skipping a huge chunk of computational effort since this is c++ vs javascript string manipulation. (btoa does not use proper buffers for binary data but strings instead) – GottZ Aug 26 '23 at 21:31
  • Thank you all for your responses they are super helpful. – Elise J Aug 26 '23 at 22:32
  • @GottZ Hm, I’m not sure the implementation is specified, only the behavior—either approach does the same thing *(roughly; you have to trim the URL if you just want the base64 part)*. Curious if there’s any benchmarking, seems like there shouldn’t be a huge difference :shrug: – Dave Newton Aug 28 '23 at 18:36
  • FileReader uses native binary c++ arrays, btoa uses utf16. thus why btoa and atob are always bad in dealing with encoded utf8 data. (I'm just speaking from in-depth knowledge of both v8 and spidermonkey here) essentially you are turning file contents into a utf16 string, shoving it into btoa and getting another utf16 string out, while FileReader returns a iterator that skips a costly convertion in the progress when doing a readAsDataURL. also in terms of memory management, using btoa for this would create more garbage for the garbage collector to cleanup afterwards. – GottZ Aug 29 '23 at 16:14

0 Answers0