在Ionic 5 + capacitor中,这是我最终能够同时监视上传并获取完成的文件名的方法。
代码来自谷歌自己的文档和一些谷歌搜索(包括
https://ionicthemes.com/tutorials/about/ionic-firebase-image-upload等)。
它使用画布(据我所知)从图像生成一个base64字符串。这个方法可行,而Ionic的File和Base64则不行。
在页面上,我有一个<ion-progressbar>显示百分比(this.downloadProgress),如果它>0。我还有一个<ion-img>,其中src=this.imageUrl,在上传图片时显示图片。
我无法让上面回答中的任何技术方法工作,甚至无法编译。但我不知道为什么。
另一个注意点是,一些示例代码使用function()而不是箭头语法
encodeImageUri(imageURI, function(image64) {
需要将其重写为箭头语法以绑定/传递“this”到调用的函数,如下所示:
encodeImageUri(imageURI, image64 => {
uploadImage(imageURI) {
console.log(`try upload ${imageURI}`)
let storageRef = firebase.storage().ref();
let imageRef = storageRef.child('image').child('imageName');
this.encodeImageUri(imageURI, image64 => {
const uplTask = imageRef.putString(image64, 'data_url');
uplTask.on('state_changed',
snapshot => {
var progress = (snapshot.bytesTransferred / snapshot.totalBytes);
console.log('Upload is ' + progress * 100 + '% done');
this.downloadProgress = progress;
},
error => {
console.log('upload error');
},
() => {
uplTask.snapshot.ref.getDownloadURL()
.then(downloadURL => {
console.log('File available at', downloadURL);
this.imageUrl = downloadURL;
this.downloadProgress = -1;
});
}
);
});
}
encodeImageUri(imageUri, callback) {
var c = document.createElement('canvas');
var ctx = c.getContext("2d");
var img = new Image();
img.onload = function () {
var aux:any = this;
c.width = aux.width;
c.height = aux.height;
ctx.drawImage(img, 0, 0);
var dataURL = c.toDataURL("image/jpeg");
callback(dataURL);
};
img.src = imageUri;
};
当然,这有点无聊,因为它总是在覆盖相同的Firebase存储文件 :) 但这是可以解决的。
taskSnapshot.getDownloadUrl()
,而不是taskSnapshot.getMetadata().getDownloadUrl()
。 - Anggrayudi HaddOnSuccessListener()
方法内调用该方法。 - Isabel Alphonse