2

I have File object (audio which I got by <input type=file />).

I want to send it on the server to save in storage.

I will send json that containt base64-string which I want to get from the file object.

I 'm confused about what function of fileReader interface should I choose to convert file in base64. Now I use readAsBinaryString:

function getBase64(file) {
  return new Promise ( (res,rej) => {
    var reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = function () {
      res(reader.result);
    };
  })
}

With this method I save audio-file to server, after I download it and change extension like was before (mp3 in my case) and the audio isn't playing. I see an error about codecs.

Maybe I missed something important in my chain of action, i don't know. Thank you in advance.

peteb
  • 18,552
  • 9
  • 50
  • 62
Alexander Knyazev
  • 2,692
  • 4
  • 15
  • 25

1 Answers1

2

readAsBinaryString represents the binary data encoded within javascript strings. Due to encoding differences between client and server, there is a possibility of data corruption. Which seems to be the case here.

As per documentation here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsBinaryString readAsBinaryString is deprecated in favour of readAsArrayBuffer, which reads the file into an ArrayBuffer. An ArrayBuffer would contain a more consistent representation of the bytes in your binary file. However, converting ArrayBuffer to base64 can still be slightly tricky.

Since you are interested in Base64 encoded binary data, I would recommend using readAsDataURL method on FileReader instance. It will read the file contents directly as Base64 encoded string. There is some additional information prepended, to make it proper data uri, you can strip it off if need be. Have a look at readAsDataURL documentation here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

d_shiv
  • 1,670
  • 10
  • 8
  • [this answer](https://stackoverflow.com/a/52311051/1221537) gives an example of how to strip off the "additional information" mentioned here, as well as addressing base64 "padding" – adamdport Aug 12 '22 at 14:32