使用REST API将文件上载到Firebase存储

cni*_*nic 11 javascript bash jquery json firebase

目前,Firebase文档指导您使用JavaScript库将文件上传到Firebase存储.

我正在运行没有安装NodeJS的服务器.是否可以通过Firebase REST API上传图像,音频等文件?

目前我在bash脚本中使用curl来发送JSON.我不希望在数据库字段中存储base64编码,我希望将文件存储在存储部分内的文件夹中.

存储文件夹如下所示:

存储文件夹

Sun*_*Bee 15

可以使用 REST API 将文档上传到 Firebase 存储。我已经用Python实现了requests库来设置 HTTP 标头并发出 POST 请求。该过程在其他语言或 cURL 中应该类似。

无需授权即可上传:

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
Run Code Online (Sandbox Code Playgroud)

这会将图像上传到名为“stash”的文件夹。请务必在 URL 中使用 %2F 而不是正斜杠。此外,您还需要使用 Firebase 规则公开您的存储桶。成功的响应将返回如下 JSON:


    {'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>'}
Run Code Online (Sandbox Code Playgroud)

要使用身份验证上传,过程是相同的,只不过您通过 HTTP 标头传递身份验证令牌(使用用于身份验证的 REST 端点获得)。像这样修改函数中的一行代码。

    headers = {"Content-Type": "image/png", "Authorization": "Bearer "+auth_token}
Run Code Online (Sandbox Code Playgroud)

下载 URL 是 url2file,并添加了 API 响应中的“downloadTokens”。添加:'?alt=media&token=',后跟令牌字符串。

该示例展示了如何将图像添加到 Firebase 存储,并且可以通过调整此模式使用 REST API 执行所有 CRUD 操作。


小智 9

Firebase存储使用Google云端存储,因此您可以使用GCS REST API获得90%的存储空间.(博士在这里.)

有几点不同.

  1. 在您通过Firebase Storage SDK访问URL之前,不会自动生成下载URL.
  2. 您将无法使用Firebase身份验证通过GCS REST端点上载.您需要设置OAuth(您可以通过身份验证进行Google登录)或服务帐户.(这是一个如何从Node.js到GCS进行身份验证的示例.)