python - 无法从 python 服务器将图像上传到 Firebase 存储
问题描述
我正在创建一个 android 应用程序,它将图像发送到 python 服务器,我想从我的 python 服务器将接收到的图像上传到 firebase 存储。我的问题是,当我尝试从 python 服务器上传接收到的图像时,只有文件名存储在指定的集合中,但我的图像没有上传。我的 Firebase 存储看起来像这个 Firebase 存储屏幕截图
在随附的屏幕截图中,以 Actual 开头的第一张图片是我从 android 上传的图片,第二张以 processed 开头的图片是我尝试从 python 上传但无法上传的图片。文件类型也不同于从android上传的文件类型。下面是我用来从服务器上传图像的代码: 我从 android 接收图像的函数:
def handle_request():
print(flask.request.files)
print(flask.request.form)
imagefile = flask.request.files['image']
userID = flask.request.form['user_ID']
upload_to_firebase(imagefile, filename, userID)
将图像存储到 Firebase 存储的函数。
def upload_to_firebase(file, filename, userID):
firebase = Firebase(config)
firebase = pyrebase.initialize_app(config)
storage = firebase.storage()
storage.child(userID + "/" + filename + "/Processed_" + filename+"").put(file)
downloadURL = storage.child(userID + "/" + filename + "/Processed_" + filename+"").get_url(None)
有什么方法可以在发送图像时传递内容类型 image/jpeg 或任何其他可以解决此问题的方法。我已经搜索了很多这个解决方案,但到目前为止没有一个有效。
解决方案
请注意,如Firebase 文档中所述:
您可以将 Admin SDK 返回的存储桶引用与官方 Google Cloud Storage 客户端库结合使用,以上传、下载和修改与您的 Firebase 项目关联的存储桶中的内容
因此,您需要将您的upload_to_firebase
函数修改为类似于此处在Python 的 Google Cloud Storage 客户端库的相关部分中解释的内容:
from google.cloud import storage
def upload_blob(bucket_name, source_file_name, destination_blob_name):
"""Uploads a file to the bucket."""
# bucket_name = "your-bucket-name"
# source_file_name = "local/path/to/file"
# destination_blob_name = "storage-object-name"
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename(source_file_name)
print(
"File {} uploaded to {}.".format(
source_file_name, destination_blob_name
)
)
您可以从使用 Firebase Admin SDK 定义的存储桶对象的名称属性bucket_name
中获取变量(例如,如果您使用项目的默认存储桶):
import firebase_admin
from firebase_admin import credentials
from firebase_admin import storage
cred = credentials.Certificate('path/to/serviceAccountKey.json')
firebase_admin.initialize_app(cred, {
'storageBucket': '<BUCKET_NAME>.appspot.com'
})
bucket = storage.bucket()
并且source_file_name
将对应于为您的 Flask 应用程序提供服务的服务器中上传图像的完整路径。
请注意,如果没有正确删除或管理上传到 Python 服务器的文件,您最终可能会遇到磁盘空间问题,因此在这方面要小心。
推荐阅读
- android - 赋值不是表达式,在这种情况下只允许使用表达式 - Kotlin
- php - How to Limit Excerpt Length in $category->description in archive-products.php WordPress?
- c# - 如何将多个 OData 微服务缝合(合并、连接……)在一起
- exchange-server - 自定义事件 ID
- arrays - 可被给定小素数整除的大小为 3 的子集的数量
- swift - 如何处理具有相同名称的快速类?
- java - @Qualifier 可以“看到”一连串的依赖关系吗?
- javascript - Javascript - 从外部脚本中删除所有副作用
- c# - ASP .NET MVC Windows 授权不起作用
- r - 覆盖不同的 ggplot2 对象