如何将本地图像从Python上传到Firebase?

时间:2020-04-18 08:01:36

标签: python firebase

我正在尝试将本地磁盘映像上传到Firebase。我是Firebase模块的新手。有人可以解释该怎么做吗?我尝试在线搜索,并能够提供此代码。我正在使用firebase_admin库。

def upload2firebase():

    cred = credentials.Certificate(
        r"*.json")
    firebase_admin.initialize_app(cred, {
        'storageBucket': '<my app name>.appspot.com'
    })


    bucket = storage.bucket()
    imageBlob = bucket.blob(os.path.basename(r'C:\Users\VINAY\.PyCharmCE2018.2\config\scratches\Test.png'))
    imageBlob.upload_from_string()
    print(imageBlob.public_url)
    return imageBlob.public_url

1 个答案:

答案 0 :(得分:0)

def upload2firebase():

cred = credentials.Certificate(
    "./gold-price-tracker-caa9e-firebase-adminsdk-9e39d-72694e4d52.json")
firebase_admin.initialize_app(cred, {
    'storageBucket': 'gold-price-tracker-caa9e.appspot.com'
})

img_src = "sample_image.png"
bucket = storage.bucket()
blob = bucket.blob(img_src)

# Create new token
new_token = uuid4()

# Create new dictionary with the metadata
metadata = {"firebaseStorageDownloadTokens": new_token}

# Set metadata to blob
blob.metadata = metadata

# Upload file
blob.upload_from_filename(filename="./Test.png", content_type='image/png')
blob.make_public()
return(blob.public_url)
    #
    #
    # bucket = storage.bucket()
    # image_data = ""
    # with open("./Test.png", "rb") as img_file:
    #     image_data = base64.b64encode(img_file.read())
    #
    # blob = bucket.blob('test.png')
    # blob.upload_from_string(image_data)
    # return blob.public_url