AngularFire上传并获取下载URL

时间:2018-08-09 14:02:34

标签: javascript angular5 firebase-storage angularfire2

我正在尝试上传到我的存储桶,然后在上传完成后立即将URL下载到该上传文件。此操作以前曾起作用,但由于某种原因已停止。

我的控制台打印仅返回null。我希望有一个解决方案,甚至是更好的方法。任何帮助都会很棒!

我正在使用Angular 5。

这是我当前的方法:

  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);
        });
      }
    });
  }

2 个答案:

答案 0 :(得分:0)

这是我在Ionic应用程序中用来上传最多5张图片的组件的一部分

  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);
      }
    );
  }

代码的相关部分是:

  1. 在上传流时使用它代替
  2. 使用多个变量来显示进度条并更新进度,并使用最后一个func来获取url并在视图中做一些事情
  3. 在我的应用中,有一个组件可以处理上传和删除图像的过程。

答案 1 :(得分:0)

这是我使用angularfire 2进行文件上传过程编码的方式。

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);
    });   
  });
}