Firebase Extensions使用AngularFire调整图像大小后,如何获取新的下载URL?

问题描述

在Firebase扩展程序调整图像大小后,需要获得调整图像URL的帮助。

在使用下面的代码之前,我可以这样做。但是,激活该功能后,图像不会显示出来。在比较了Firestore上的imgurL和Firebase存储器上的下载URL之后,这些函数似乎将图像尺寸(500x500)添加到了路径名的后面。 (image_123-> image_123_500x500)。

  1. 我尝试查找如何在Firebase Extension设置中排除该错误。但是没有运气。 (可能会错过)

  2. 我认为下一步是通过调整图像大小后获取URL来调整代码本身。但是我要么变得不确定,要么出错。另外,我无法通过先“上传图片”然后“提交表单”来实现不创建两个独立的功能

      upload($event: any) {
        this.file = $event.target.files[0];
        this.image = true;
      }


        async submitHandler() {
        if (this.image === true) {
          // Generate random ID
          const randomId = Math.random().toString(36).substring(2);
          // The storage path
          const path = `products/${this.productForm.value.model}_${randomId}`;
          // Reference to storage bucket
          const ref = this.afStorage.ref(path);
          // The main task (upload Image to Firestorage)
          this.task = this.afStorage.upload(path,this.file);
    
          // Get the URL from ref (Firestorage),added to the form and submit to FIrestore
          this.task
            .snapshotChanges()
            .pipe(
              finalize(async () => {
                this.downloadURL = await ref.getDownloadURL().toPromise();
                /*this.afs
                .collection('products')
                .add({ downloadURL: this.downloadURL,path });*/
                this.loading = true;
                this.productForm.value.imgurl = this.downloadURL;
                this.productForm.value.user = this.auth.getUserEmail();
                const formValue = this.productForm.value;
                try {
                  await this.afs.collection('products').add(formValue);
                  console.log(formValue);
                  this.success = true;
                } catch (err) {
                  console.error(err);
                }
              })
            ) // To display URL
            .subscribe();
    
          this.loading = false;
        } else {
          alert('Please upload the picture of product');
        }
      }

解决方法

实际上,如官方文档here所述,“调整大小图像”扩展名会将高度和宽度添加到文件名中。如答案here所述,安装扩展名后,它要求您提供用于存储调整大小的文件的路径。因此,要返回downloadURL,将取决于您为路径添加的名称,或者是否未添加任何名称。

因此,您将需要在安装扩展程序时从设置的路径中引用文件。然后,您需要根据为新尺寸设置的大小来处理文件名。您可以尝试按照以下方式将尺寸添加到文件名中。以下代码基于此答案here,我认为这将对您有所帮助。

function resizedName(fileName,dimensions = '500x500') {
  const extIndex = fileName.lastIndexOf('.');
  const ext = fileName.substring(extIndex);
  return `${fileName.substring(0,extIndex)}_${dimensions}${ext}`;
}

总而言之,您将需要在新路径上返回文件,并且如果它们与原始文件位于同一路径,则需要修改文件名,并在其中添加宽​​度和高度名称。