如何在Ionic 4中将图片上传到Firebase?

4

我无法将图片上传到Firebase。需要帮助。

有谁熟悉在Ionic 4.0中如何上传图片到Firebase?以下是我曾经在Ionic 2中使用的代码,但现在当我点击上传图片到Firebase的按钮时,它需要大约30秒才能响应(click),然后它从未将图片上传到Firebase。

我尝试使用此教程中的示例,但无法摆脱与ImagePicker相关的错误。https://ionicthemes.com/tutorials/about/ionic-firebase-image-upload 非常感谢任何帮助。

      <ion-card-content>
            <div>
                <img src="assets/img/add-an-image.png" (click)="selectPhoto()"/>     
            </div>
        </ion-card-content>

constructor(
    private afAuth: AngularFireAuth,
    private camera: Camera) {

        this.afAuth.authState.subscribe(user => {
        this.userId = user.uid;
        this.myPhotosRef = firebase.storage().ref(`/Photos/${ this.userId }/`);
      });
    }

  selectPhoto(): void {
    const options: CameraOptions = {
      quality: 100,
      destinationType: this.camera.DestinationType.FILE_URI,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
    };

    this.camera.getPicture(options).then((imageData) => {
      console.log(options, 'get pic');
      this.myPhoto = imageData;
      this.uploadPhoto(this.myPhoto);
    }, error => {
      console.log('ERROR -> ' + JSON.stringify(error));
    });
  }

  private uploadPhoto(photoName: string): void {
    this.myPhotosRef.child(photoName)
      .putString(this.myPhoto, 'base64', { contentType: 'image/png' })
      .then((savedPicture) => {
        this.myPhotoURL = savedPicture.downloadURL;
      });
  }


要求我们推荐或寻找书籍、工具、软件库、教程或其他外部资源的问题在 Stack Overflow 上是不适合的,因为它们往往会吸引主观的答案和垃圾邮件。相反,请描述问题以及已经采取的解决方法。 - André Kool
你说:“我尝试使用这个教程中的示例”。你指的是哪个教程? - Narm
https://ionicthemes.com/tutorials/about/ionic-firebase-image-upload - D.Hodges
4个回答

2

0

0

有很多方法可以做到这一点,您可以使用响应和错误来跟踪发生了什么。启用Web控制台日志。

以下是如何执行并跟踪错误的示例:

uploadFile(file){
const fileName = this.generateRandomName() + '.jpg';
const fileRef = firebase.storage().ref().child('tptimagefolder/'+ fileName);
const uploadTask = fileRef.put(file);

return new Promise((resolve, reject) => {
    uploadTask.on('state_changed', snapshot => {
},  error => {
      reject(error);

}, () => {
  uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
    console.log('teste resolve url'+downloadURL);

    resolve ( {fileName, downloadURL});
  });

});

}); }

this.generateRandomName() 是一个用于创建名称的函数,如果你不需要它,可以不使用它。


0
我按照Ionic Themes的教程上传图片到Firebase Storage:https://ionicthemes.com/tutorials/about/ionic-firebase-image-upload 它说这是为Ionic 3准备的,但在Ionic 4中也可以使用。
根据教程,Storage与firestore和fire storage模块是分开的,因此在您的应用程序模块中,您必须像这样导入firebase:
import * as firebase from "firebase";
firebase.initializeApp(environment.firebaseConfig)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接