AngularFire upload and get download URL

此生再无相见时 提交于 2019-12-11 01:56:23

问题


I'm trying to upload to my Storage bucket and then get the downloadURL to that uploaded file right after the upload is done. This was working previously but has since stopped for some reason.

My console print is just returning null. I was hoping for a solution or even a better way of doing this. Any help would be awesome!

I'm using Angular 5.

Here is my current method:

  upload(event) {
    this.showProgressBar = true;
    const randomId = Math.random().toString(36).substring(2);
    this.ref = this.afStorage.ref(randomId);
    this.uploadTask = this.ref.put(event.target.files[0]);
    this.uploadProgress = this.uploadTask.percentageChanges().subscribe(progress => {
      console.log(progress);
      document.querySelector('#progressBar').style.width = progress + "%";
      if(progress === 100){
        this.showProgressBar = false;
        this.showUploaded = true;
        this.downloadURL = this.uploadTask.downloadURL().subscribe(url => {
          console.log(url);
        });
      }
    });
  }

回答1:


Here is the way that I coded using angularfire 2 for the file uploading process.

public selectedFile: FileList;
chooseFile(event) {
  this.selectedFile =  event.target.files;
}

uploadImage() {
  const file = this.selectedFile.item(0);
  const key = 'uploads/' + '/' + Math.floor(Math.random() * 1000000) + file.name;
  const upload = this.stroge.upload(key, file).then(() => {
    const ref = this.stroge.ref(key);
    const downloadURL = ref.getDownloadURL().subscribe(url => {
      this.Updateprofile(url);
    });   
  });
}



回答2:


Here is the part of the component I’m using in an Ionic app to upload up to 5 pics

  uploadPicture(i) {
    let that=this;
    this.cameraPlugin.getPicture({
        quality: 100,
        destinationType: this.cameraPlugin.DestinationType.DATA_URL, 
        sourceType: this.cameraPlugin.PictureSourceType.CAMERA, 
        allowEdit: true,
        encodingType: this.cameraPlugin.EncodingType.PNG,
        //targetWidth: 500, 
        //targetHeight: 500, 
        saveToPhotoAlbum: true
      }).then(
      imageData => { 
        // Send the picture to Firebase Storage
        const selfieRef = this.addPictureFile();
        var uploadTask = selfieRef.putString(imageData, 'base64', {contentType: 'image/png'});
        // Register three observers:
        // 1. 'state_changed' observer, called any time the state changes
        // 2. Error observer, called on failure
        // 3. Completion observer, called on successful completion
        that.uploading = true;
        that.picsCtrl[i].buttonDisabled = true;
        uploadTask.on('state_changed',   
          function(snapshot) {
            // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
            var progress = (uploadTask.snapshot.bytesTransferred / uploadTask.snapshot.totalBytes) * 100;
            that.loadProgress = progress;
            switch (uploadTask.snapshot.state) {
              case firebase.storage.TaskState.PAUSED: // or 'paused'
                console.log('Upload is paused');
                break;
              case firebase.storage.TaskState.RUNNING: // or 'running'
                console.log('Upload is running');
                break;
            }
          }, function(error) {
          // Handle unsuccessful uploads
          }, function() {
            // Handle successful uploads on complete
            // For instance, get the download URL: https://firebasestorage.googleapis.com/...
            uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
              var imageURL = selfieRef.getDownloadURL().then(url => {
                that.uploading = false;
                that.picsCtrl[i].imgSrc = url;
                that.picsCtrl[i].buttonHidden = !that.picsCtrl[i].buttonHidden;
                that.picsCtrl[i].imgHidden = !that.picsCtrl[i].imgHidden;
                that.addPictureRef(url)
                  .then( keyRef => {
                    that.picsCtrl[i].imgKey = keyRef.key;
                    that.picsCtrl = that.createBucket(that.picsCtrl);
                  });
                });

            });
          });
        },
      error => {
      console.log(error);
      }
    );
  }

The relevants parts of the code are:

  1. Using that instead of this when the stream is being uploaded
  2. The use of several vars to show the progress bar and update the progress and the final func to get the url and do some stuff in the view
  3. In my app there’s a component that handles the process of uploading and removing images.


来源:https://stackoverflow.com/questions/51769074/angularfire-upload-and-get-download-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!