【发布时间】:2021-10-06 09:29:26
【问题描述】:
我正在使用 Firebase 创建一个网站。用户应该能够上传和更新他们的个人资料图片,只要它小于 10mb,并且是 .jpg、.png 或 .gif 文件。
应该发生什么:
- 用户上传有效图片
- 在 Firebase 存储中创建或更新引用
/users/{uid}/profileImage - 使用
getDownloadURL()方法获取图片的 URL,并将其作为文本存储在 Firestore 中的用户个人资料信息下 - 使用该 URL 作为头像的
src。
当我尝试在我的计算机 (Windows 10) 上执行此操作时,它运行良好。但是,当我尝试在手机(iPhone 8;iOS 14.7.1)上执行此操作时,它不起作用。从手机上传的图片到达/users/{uid}/profileImage,但由于权限问题,即使用户按照规则在手机浏览器上进行了身份验证,也无法正确获取downloadURL。
以下是 (1) 获取文件和 (2) 更新用户头像的代码:
// Grab dp img and store it in file var
let file = {}
const chooseFile = (e) => {
// Get the file from local machine
file = e.target.files[0]
console.log(file )
}
// Store dp in storage as file, and db as link
const updateDp = (currentUser) => {
// Check if new dp has been added/exists.
if ("name" in file) {
// Check if uploaded file is an image
if (file.type !== "image/jpeg" && file.type !== "image/png" && file.type !== "image/gif") {
alert("You can only upload .jpeg, .jpg, .png and .gif under 10mb")
return
}
// Check image file size
if (file.size/1024/1024>10) {
alert("The image size must be under 10mb")
return
}
// Create storage ref & put the file in it
storage
.ref("users/" + currentUser.uid + "/profileImage")
.put(file)
.then(() => {
// success => get download link, put it in DB, update dp img src
storage
.ref("users/" + currentUser.uid + "/profileImage")
.getDownloadURL()
.then(imgURL => {
db
.collection("users")
.doc(currentUser.uid)
.set({
dp_URL: imgURL,
dp_URL_last_modified: file.lastModifiedDate
}, {
merge: true
})
document.querySelector("#nav_dp").src = imgURL;
})
console.log("success")
}).catch(() => {
console.log(error.message)
})
} else {
console.log("Empty/no file")
}
}
以下是我的 Firebase 存储规则:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /users/{uid}/{profileImage} {
allow read: if request.auth!=null;
allow write: if request.auth!=null && request.auth.uid == uid;
}
}
}
【问题讨论】:
标签: javascript firebase google-cloud-firestore firebase-authentication firebase-storage