【发布时间】:2021-03-13 02:56:21
【问题描述】:
基本上我的问题是我似乎无法将照片上传到我的 Firebase 项目。我能够将用户信息推送到Realtime Database,并且我也成功集成了Firebase Authentication,我将其与 Flask Sessions 一起使用以保持用户登录。看来,为了保存文件/照片,您需要使用 @ 987654323@,但我不知道怎么做。
用户可以单击“/upload-image”路径中的“上传文件”按钮,现在我已将图像保存(在用户上传后)到与 fiddl.py 相同目录中的文件夹中文件。
以下所有代码都在我的Fiddl.py file 中。
这是我的 Firebase 初始化:
注意,storageRef 是我尝试过的,但存储中没有 ref() 这样的东西,所以我得到了错误。我也有storage,因为我相信它引用了我的项目存储。
#initialize database
firebase = pyrebase.initialize_app(json.load(open('firebase/firebaseConfig.json')))
auth = firebase.auth()
db = firebase.database()
#storageRef = firebase.storage.ref() #Points to the root reference
app.secret_key = os.urandom(24) #secret key:track if user is logged in
storage = firebase.storage("gs://fiddl-dev.appspot.com")
这是我用来将用户上传的图像存储在本地文件夹/FIDDL/Photo test 中的配置。为了您的方便,我缩短了路径的名称。 旁注我希望以后将这些配置添加到他们自己的文件中以确保安全,但仍然不能 100% 确定这些配置应该如何工作。除此之外,我还有让用户从他们的设备上传照片的路线。
#temp image upload location
#TODO: put these in a private config file
app.config["IMAGE_UPLOAD"] = "/FIDDL//photosTest"
app.config["ALLOWED_IMAGE_EXTENSIONS"] = ["PNG", "JPG", "JPEG"]
app.config["MAX_IMAGE_FILESIZE"] = 1.5 * 1024 * 1024 #1,572,864 Bytes or 1572.864 KB
# Upload Image
@app.route('/upload-image', methods=["GET", "POST"])
def upload_image():
try:
print(session['usr']) #this is equal to logged in users id token-> user['idToken']
app.logger.info("A user is already logged in")
#TODO: add a logout button, make sure to delete session for use on logout
# Alert Messages
noFileName = 'Image must have a file name.'
badFileSize = 'Image file size is too large.'
badFileName = 'That image extension or file name is not allowed'
dataAdded = 'User photos added to realtime database'
if request.method == "POST":
if request.files:
image = request.files["image"] #works the same as user input emal in register, get the image file
print(image)
#Grab the file size
image.seek(0, os.SEEK_END)
file_size = image.tell()
app.logger.info("Image File Size: ")
app.logger.info(file_size)
#Check the image file size
if not allowed_image_filesize(file_size):
#TODO: alert user on screen of the issue
app.logger.info(badFileSize)
return redirect(request.url)
#Check for file name
if image.filename == "":
app.logger.info(noFileName)
return redirect(request.url)
#Check if image has correct type
if not allow_image(image.filename):
app.logger.info(badFileName)
return redirect(request.url)
else:
filename = secure_filename(image.filename) #create new secure file name
app.logger.info(filename)
print(auth.current_user)
#Add data to realtime database
#TODO: figure out how to store photos in firebase
#Update progress
app.logger.info(dataAdded)
#image.save(os.path.join(app.config["IMAGE_UPLOAD"], filename)) #save images to /photosTest for testing
#print("image saved")
return redirect(request.url)
except KeyError:
app.logger.info("No user logged in, redirect to login")
return redirect(url_for('login'))
return render_template("upload_image.html")
这里是 Firebase/Develop/Storage/Rules 的规则。我正在使用 Firebase 身份验证,但仍然收到错误消息:
"code": 403,
"message": "Permission denied. Could not perform this operation"
}
规则:
rules_version = '2';
// Grants a user access to a node matching their user ID
service firebase.storage {
match /b/fiddl-dev.appspot.com/o {
// Files look like: "user/<UID>/path/to/file.txt"
match /user/{userId}/{allPaths=**} {
allow write: if request.auth != null;
allow read: if true;
}
}
}
我知道这里没有真正需要解决的问题,但任何朝着正确方向的点都会非常棒!谢谢!
【问题讨论】:
-
如here 所述,只需执行
firebase.storage().child("images/example.jpg").put("example2.jpg")之类的操作 - 您是否尝试过该代码? -
我相信它正在工作,因为我的存储规则拒绝了我的
put并带有“错误”:{“代码”:403,“消息”:“权限被拒绝。无法执行此操作" } -
嗯,您在 Firebase 项目中设置 Firebase 存储了吗?另外,也许检查您的规则是否允许您的服务器添加文件
-
好的,你的修复成功了!非常感谢@BlunderingPhilosopher!现在编辑我的规则并弄清楚如何正确地只允许经过身份验证的用户使用
put照片。我想我可能需要使用 Firebase 管理员。 -
感谢您的所有帮助@BlunderingPhilosopher!我一定会读一读,我将对我的原始帖子进行新的工作编辑,因为我需要进行一些其他修复才能使一切正常工作!最好的。
标签: firebase flask firebase-storage pyrebase