30

Right now, the Firebase documentation guides you on uploading files to Firebase Storage by using their JavaScript library.

I am operating a server without NodeJS installed. Is it possible to upload files like image, audio, through the Firebase REST API?

At the moment I am using curl in a bash script to send JSON. I would prefer not to store base64 encoding in a database field, I want the file to be stored in a folder inside the Storage section.

Storage folder shown below:

Storage Folder

6
  • You don't need a nodejs server, firebase storage is client side, you just need an html file with the firebase library included and with a javascript script..... Commented Jun 4, 2016 at 14:23
  • @Ymmanuel it is being run on a server with no browser. You can't run a HTML page, sorry. Commented Jun 4, 2016 at 14:25
  • Ok ok i understand now...right now only the realtime database can be accessed using REST API... so i don't think you can upload a file that way without a nodes server Commented Jun 4, 2016 at 14:32
  • Understood. Do you know if the JavaScript library is using WebSockets for streaming data? Commented Jun 4, 2016 at 15:25
  • sorry i don't know Commented Jun 4, 2016 at 15:33

3 Answers 3

18

It is possible to upload a document to Firebase storage using the REST API. I have implemented in Python with the requests library to set HTTP headers and make a POST request. The process should be similar in other languages or with cURL.

To upload without auth:

def firebase_upload():
"""
Executes a POST request to upload an image to Firebase Storage.
DEMONSTRATION ONLY, USE NO FURTHER!
args: None
returns: response (json) with the response to the request
usage: res = firebase_upload()
"""
    response = None

    file2upload = "/Your/Path/To/your_pic.png"
    file_binary = open(file2upload, "rb").read()

    # HTTP
    url2file = 'https://firebasestorage.googleapis.com/v0/b/<your-project-ID.appspot.com>/o/stash%2Fyour_pic.png'
    headers = {"Content-Type": "image/png"}

    r = requests.post(url2file, data=file_binary, headers=headers)
    response = r.json()

    return response

This uploads the image to a folder named 'stash'. Be sure to use %2F instead of forward-slash in the URL. Also, you will need to make your storage bucket public using Firebase Rules. A successful response will return JSON like the following:


    {'name': 'stash/your_pic.png',
    'bucket': '<your-project-ID>.appspot.com',
    'generation': '1608437408388390',
    'metageneration': '1',
    'contentType': 'image/png',
    'timeCreated': '2020-12-20T04:10:08.388Z',
    'updated': '2020-12-20T04:10:08.388Z',
    'storageClass': 'STANDARD',
    'size': '52628',
    'md5Hash': 'mmkqwEek6tMAZmvooQ9X7g==',
    'contentEncoding': 'identity',
    'contentDisposition': "inline; filename*=utf-8''your_pic.png",
    'crc32c': 'fhlSmw==',
    'etag': 'CKaq+6LY2+0CEAE=',
    'downloadTokens': '<secure_token>'}

To upload with auth, the procedure is the same except you pass an auth token (obtained using the REST end-point for auth) with the HTTP header. Modify one line of code in the function like so.

    headers = {"Content-Type": "image/png", "Authorization": "Bearer "+auth_token}

The download URL is the url2file with the addition of 'downloadTokens' from the API response. Add: '?alt=media&token=' followed by the token string.

The example shows how to add an image to Firebase storage and all CRUD operations can be performed with the REST API by tweaking this pattern.

Sign up to request clarification or add additional context in comments.

3 Comments

This answer has useful info for obtaining an auth token: stackoverflow.com/questions/49905450/…
If you are searching for a way to add metadata to your files with the rest api, see the following answer: stackoverflow.com/a/70181813/8634683
Have a way to delete a doc from storage using something like this?
17

Firebase Storage uses Google Cloud Storage under the hood, so you can use the GCS REST API to get 90% of the way there. (Docs here.)

There's a couple differences.

  1. Download URLs won't be automatically generated until you access it through the Firebase Storage SDK.
  2. You won't be able to use Firebase Authentication to upload through the GCS REST endpoint. You'll either need to set up OAuth (which, you might be able to get through Google Sign in with Authentication) or a service account. (Here's an example of how you can authenticate from Node.js to GCS.)

Comments

1

I found Sun Bee's answer really helpful, just wanted to add some notes for adding metadata since that wasn't straightforward for me.

def firebase_upload():
"""
Executes a POST request to upload an image to Firebase Storage.
DEMONSTRATION ONLY, USE NO FURTHER!
args: None
returns: response (json) with the response to the request
usage: res = firebase_upload()
"""
    response = None

    file2upload = "/Your/Path/To/your_pic.png"
    bucket = '<your-project-ID.appspot.com>'
    storage_path = 'cloud/path/to/your/pic.png'.replace('/', '%2F')
    token = '<your-firebase-token>'

    # HTTP
    url2file = f'https://firebasestorage.googleapis.com/v0/b/{bucket}/o/{storage_path}'
    headers = {
                "Authorization": f"Firebase {token}",
                "X-Goog-Upload-Protocol": "multipart"
              }

    files = {                                                                                                                                                                                                                                                    
      'metadata': (None, '{"metadata":{"mykey":"myvalue"}}', 'application/json'),                                                                                                                                                                        
      'file': open(file2upload, 'rb'),                                                                                                                                                                                                             
            }                                                                                                                                                                                                                                          
    r = requests.post(url, files=files, headers=headers)

    response = r.json()

    return response

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.