如何在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');
}
}

事实上,正如这里的官方文档中所述,Resize Image扩展名将在文件名中添加高度和宽度。正如这里的回答所阐明的,一旦您安装了扩展,它就会要求您提供一个存储调整大小的文件的路径。因此,对于返回downloadURL,它将取决于您为路径添加的名称,或者您是否没有添加任何名称。

因此,在安装扩展插件时,您需要从您设置的路径引用文件。然后,您需要根据为新尺寸设置的大小来处理文件的名称。您可以尝试以下方法将尺寸添加到文件名中。下面的代码基于这个答案,我认为这应该作为一个起点对您有所帮助。

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

总之,您需要处理新路径以将文件返回到那里,如果它们与原始文件位于同一路径,则需要修改它们的名称,并在名称中添加宽度和高度。

最新更新