Ionic 2 应用程序:在 firebase 存储中上传相同的图像
Ionic 2 app: Same image upload in firebase storage
我正在尝试在 Ionic 2 中制作聊天应用程序。因此,当用户在聊天中发送图像时,我将其上传到 Firebase 存储,它为我提供了该图像的 URL。当用户再次发送相同的图片时,该图片会再次上传到 Firebase 并覆盖之前的图片并提供新的 URL,这会导致发送的旧图片出现问题。
我知道最明显的解决方案是通过重命名来上传图片,但我不想多次上传同一张图片。对此有更聪明的解决方案吗?请提出建议。
您可以通过调用 getDownloadUrl()
.
检查文件是否已存在于 Firebase 存储中
ref.child('example.png').getDownloadURL()
.then(url => {
// File exist
})
.catch(err => {
// File didnt exist or other error
});
编辑:
为了防止上传两个具有相同名称的不同图像,我建议使用 customMetadata,用图像的 base64 编码 MD5 哈希标记每个图像。然后在上传时遇到同名图片时使用这个hash进行比较。如果它是具有相同名称的不同图像,则您必须重命名该图像。请务必重复此过程,以处理超过 2 张图像同名的情况。
一些伪代码来说明我的意思:
uploadImg(img){
hash = create base64 md5 hash of image
do {
if(filename exist in storage){
get storage file metadata in order to get a hold of its hash
if(hash is equal to hash from storage){
use file in storage instead
}
else{
alter the filename eg. using a counter and make the do-while-loop run again
}
else{
uploadFile(img, metadata containing hash)
}
}while(other file with same name exist in storage)
}
我正在尝试在 Ionic 2 中制作聊天应用程序。因此,当用户在聊天中发送图像时,我将其上传到 Firebase 存储,它为我提供了该图像的 URL。当用户再次发送相同的图片时,该图片会再次上传到 Firebase 并覆盖之前的图片并提供新的 URL,这会导致发送的旧图片出现问题。
我知道最明显的解决方案是通过重命名来上传图片,但我不想多次上传同一张图片。对此有更聪明的解决方案吗?请提出建议。
您可以通过调用 getDownloadUrl()
.
ref.child('example.png').getDownloadURL()
.then(url => {
// File exist
})
.catch(err => {
// File didnt exist or other error
});
编辑: 为了防止上传两个具有相同名称的不同图像,我建议使用 customMetadata,用图像的 base64 编码 MD5 哈希标记每个图像。然后在上传时遇到同名图片时使用这个hash进行比较。如果它是具有相同名称的不同图像,则您必须重命名该图像。请务必重复此过程,以处理超过 2 张图像同名的情况。
一些伪代码来说明我的意思:
uploadImg(img){
hash = create base64 md5 hash of image
do {
if(filename exist in storage){
get storage file metadata in order to get a hold of its hash
if(hash is equal to hash from storage){
use file in storage instead
}
else{
alter the filename eg. using a counter and make the do-while-loop run again
}
else{
uploadFile(img, metadata containing hash)
}
}while(other file with same name exist in storage)
}