Firebase 3 + Ionic 2 + cordova-plugin-camera - 上传文件

时间:2016-06-07 04:33:22

标签: typescript angular firebase ionic2

我正在尝试使用cordova-plugin-camera将照片上传到firebase存储,但没有成功:

这是我的代码:

let options:any = {
    quality : 100,
    destinationType : Camera.DestinationType.DATA_URL,
    sourceType : Camera.PictureSourceType.CAMERA,
    allowEdit : false,
    encodingType: Camera.EncodingType.JPEG,
    mediaType: Camera.MediaType.PICTURE,
    targetWidth: 1920,
    targetHeight: 1920,
    saveToPhotoAlbum: true,
    cameraDirection: Camera.Direction.FRONT
};

Camera.getPicture(this.options).then( (imageData) => {

                let blob: any = new Blob( [imageData], { type: "image/jpeg" } );
                blob.name = 'image.jpg';

                let storageRef: any = firebase.storage().ref();
                let path: string = 'images/' + this.user.uid + '/' + Math.random().toString(36).substr(2, 9) + '.jpg';

                console.log(path);

                let uploadTask: any = storageRef.child(path).put(blob);

                uploadTask.on('state_changed', function(snapshot) {
                    console.log(snapshot);
                }, function(error) {
                    this.showAlert(error);
                }, function() {
                    var downloadURL = uploadTask.snapshot.downloadURL;
                    console.log(downloadURL);

                    console.log(this.user);

                    this.user.set({photo: downloadURL});
                });

            }, (err) => {
                this.showAlert(err);
            });

我不知道为什么,但似乎上传和我检查文件时是空的。

请帮忙吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

问题出在这个部分

let blob: any = new Blob( [imageData], { type: "image/jpeg" } );

您需要将imageData转换为base64为Blob。我建议根据此链接https://stackoverflow.com/a/16245768/3227392使用atob函数生成Blob。对于完全相同的用例,这对我有用。

但需要注意的是,DATA_URL内存很重,因此对于较大的图片可能会出现问题。