[英]How upload image to firebase storage from Ionic?
我需要帮助将图像从离子发送到Firebase存储。 因此,我用此功能拍照:
async takePicture() {
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
try {
let imageURI = await this.camera.getPicture(options);
let newImageURI = await this.cropImage(imageURI);
let imageSanitized = await this.encodeFile(newImageURI);
this.imgSrc = imageSanitized;
} catch (e) {
console.error(JSON.stringify(e));
}
}
我使用此功能进行裁剪:
cropImage(imgURI): Promise<string> {
return new Promise((resolve,reject) => {
this.cropService.crop(imgURI, { quality: 100 }).then((newImageURI: string) => {
resolve(newImageURI);
}, (err) => {
reject(err);
})
})
}
完成我用这个功能编码:
encodeFile(ImageURI: string): Promise<any>{
return new Promise((resolve, reject) => {
this.base64.encodeFile(ImageURI).then((base64File: string) => {
this.imgUri = base64File;
resolve(this.domSanitizer.bypassSecurityTrustResourceUrl(base64File));
}, (err) => {
reject(err);
})
})
}
this.imgSrc是我清理过的图像,在我的file.html中显示得很好。 但是,我需要将此图像发送到Firebase存储。 为此,我创建了以下功能:
uploadToStorage(imgString) {
console.log(imgString);
this.storage.child('exemplo.JPEG').putString(imgString, 'data_url').then((res) => {
console.log(res);
}, (error) => {
console.error(error);
});
}
imgString是从函数encodeFile获取this.domSanitizer.bypassSecurityTrustResourceUrl(base64File)或base64File的值的人。
我的上传功能没有出现错误,但是我没有获得成功,没有任何显示。
如何将图像正确发送到服务器?
我认为您可以使用以下方式将图像捕获为base64:
destinationType: this.camera.DestinationType.DATA_URL
而不是FILE_URI。
无论如何,为了记录图像,我在AngularFire2中使用了下面的代码。 这是我保存base64图像的位置。 但是,如果您的编码器将“” data:image / jpeg; base64“添加到base64字符串的开头,则可能会变得棘手。如果此代码无法正常工作,则可以尝试添加或不添加字符串。
import { AngularFireStorage, AngularFireStorageReference } from 'angularfire2/storage/public_api';
//...
const storageRef: AngularFireStorageReference = this.afStorage.ref(`images/${this.userId}/profilePic/`);
storageRef.putString(this.data.image, 'data_url', {
contentType: 'image/jpeg'
}).then(() => {
storageRef.getDownloadURL().subscribe(url => {
console.log('download url: ' + url);
//function to save download URL of saved image in database
});
})
})
我这样做:
encodeFile(ImageURI: string): Promise<any>{
return new Promise((resolve, reject) => {
this.base64.encodeFile(ImageURI).then((base64File: string) => {
this.imgUri = base64File;
...
}, (err) => {
...
})
})
}
this.imgUri存储我的图像base64编码。 但是有必要修改它的开始。 如此拆分:
let messageSplit = this.imgUri.split('data:image/*;charset=utf-8;base64,')[1];
添加在她的位置
let message64 = 'data:image/jpg;base64,' + messageSplit;
因此,上传到Firebase存储。
const filePath = `my-pet-crocodile_${ new Date().getTime() }.jpg`;
let task = this.afStorage.ref(filePath).putString(message64, 'data_url');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.