我正在使用Ionic 4将图像从相机上传到Firebase存储器。上载正常,但我很难获取上载URL。我的代码如下:
async getFromCamera(){
this.camera.getPicture({
destinationType: this.camera.DestinationType.DATA_URL,
quality: 25,
correctOrientation: true,
allowEdit:false
}).then(async (imageData) => {
var base64Image = "data:image/jpeg;base64," + imageData;
this.uploadToFireStore(base64Image).then(
(data) => console.log("done to firestore:" + data),
(err) => console.log("The error to upload is:::" + JSON.stringify(err))
)
}, (err) => {
console.log("Error found is:" + err);
});
}
uploadPercent
downloadURL
uploadToFireStore(imageData){
return new Promise<any>((resolve, reject) => {
let storageRef = this.storage.ref('/');
let imageRef = storageRef.child('myimage')
const task = imageRef.putString(imageData, 'data_url')
console.log("Task is:::" + task)
// observe percentage changes
this.uploadPercent = task.percentageChanges();
// get notified when the download URL is available
task.snapshotChanges().pipe(
finalize(() => {
this.downloadURL = imageRef.getDownloadURL()
console.log("upload percent:" + JSON.stringify(this.uploadPercent))
console.log("download url is::" + JSON.stringify(this.downloadURL))
}
)
)
.subscribe()
})
}
我看到的答复是:
upload percent:{"_isScalar":false,"source":{"_isScalar":false},"operator":{}}
/tab1-tab1-module.js:629 download url is::{"_isScalar":false}
答案 0 :(得分:2)
Firebase Storage允许您上传文件,因此您不需要上传长base64
字符串。为什么您仍要上传base64
?
我不熟悉this.camera.getPicture
方法返回的内容,但是可以肯定它是File
的一种。在这种情况下:
}).then(imageData => {
this.uploadToFireStore(imageData)
和
uploadToFireStore(imageData){
let storageRef = this.storage.ref('/');
let imageRef = storageRef.child('myimage')
const task = imageRef.upload(imageData, 'data_url')
this.uploadPercent = task.percentageChanges();
task.snapshotChanges().pipe(
finalize( async () => {
await this.downloadURL = imageRef.getDownloadURL().toPromise();
console.log('this.downloadURL', this.downloadURL)
}
)
)
.subscribe()
请注意,finalize
使用async
函数,因为imageRef.getDownloadURL()
返回一个Observable,因此我们只需要一个值,而这是此流唯一需要的值,它看起来更干净,可以将其转换为Promise。