user4550050 user4550050 - 2 years ago 415
Javascript Question

Store files in Firebase storage

I'm building a web app with Firebase and Angularjs for my frontend. I want to know if it possible to store files (any kind) in the Firebase DB.

If so what are the limitations?


Answer Source

When you send data from your client to Firebase, it is serialized into a JSON object. This limits you to only storing types that can be represented with the primitives of JSON:

  • Strings (Unicode)
  • Booleans
  • Numbers (64 bit floating point)
  • null

If your browser supports the File API and you can convert a file to a representation using the above types, then yes you can store it in Firebase (providing it's under 10mb).

If your file is encoded with Unicode then you can simply read it into a string variable then pass that to Firebase — just as you would with any other string.

If you want to work with binary files, it's a little more complicated.

Take images for example. You can read an image using the readAsDataURL method which returns a base64 encoded string, which can safely be serialized to JSON. When another user requests the data from Firebase, they can simply use the src='data:image/png;base64, syntax to correctly show the image.

There's an example project that uses this technique here.

A more complicated example might be a binary format such as a Midi file. Although you can read the file into a base64 string, you can't play it in the browser, so the user would need to download it. You can't give them a base64 string either, because most Midi players won't understand it.

This means you'll need to write an decoder for turning the base64 data back into binary, before you write it to file or offer it as a download. This will probably involve turning it into a blob, using typed arrays.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download