在 Firebase 扩展调整图像大小后,需要帮助获取调整图像大小 URL。
在我能够使用下面的代码执行此操作之前。但是,激活该功能后,图像没有显示。在比较 Firestore 上的 imgURL 和 Firebase 存储上的下载 URL 后,这些函数似乎将图像尺寸 (500x500) 添加到了路径名的后面。 (image_123 -> image_123_500x500)。
我尝试查找如何在 Firebase 扩展设置中排除它。但没有运气。 (可能会错过)
我认为下一个选项是通过在调整图像大小后获取 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中所澄清的,安装扩展后,它会要求您提供调整大小的文件的存储路径。因此,对于您返回 downloadURL
,这将取决于您为路径添加的名称,或者如果您没有添加任何名称。因此,您需要从安装扩展时设置的路径引用该文件。然后,您需要根据为新尺寸设置的大小来处理文件的名称。您可以尝试按照将尺寸添加到文件名的方式进行操作。下面的代码基于这个答案
function resizedName(fileName, dimensions = '500x500') {
const extIndex = fileName.lastIndexOf('.');
const ext = fileName.substring(extIndex);
return `${fileName.substring(0, extIndex)}_${dimensions}${ext}`;
}
总而言之,您需要使用新路径来返回文件,如果它们与原始文件位于同一路径中,您将需要修改它们的名称,将宽度和高度添加到名称中.
3个注意事项。
import { getStorage, ref, getDownloadURL } from "firebase/storage";
下面是一个 JS 函数,用于获取新的 firebase 调整大小的 URL。
async getResizedURL(originalUrl,size) {
let storageUrl = originalUrl; //originalUrl have the ORIGINAL IMAGE FIREBASE HTTP PATH. Ex: "https://firebasestorage.googleapis.com/v0/b/your-storage-bucket/o/example.jpg?alt=media&token=your-download-token"
const storage = getStorage();
const httpsReferencePath = ref(storage, storageUrl).fullPath;//For taking File path of actual image
const sizeRequired = size; //size is a string which you have provided during extension configuration.Ex:'200x200' or '100x100'
const newFilePath=this.getNewFilePath(httpsReferencePath);//Return a new string .This should be string manipulation method.If you have created a new folder for resized images.Say "resized-images" is the folder name which have all the resized-images.Add "resized-images" in the folder path.
const extension=getFileNameExtension(httpsReferencePath);//Again a string manipulation function which pops out last extension
const newResizedPath = `${newFilePath}_${sizeRequired}.${extension}`;
await getDownloadURL(ref(storage, newResizedPath)).then((url) => {
this.resizedImageUrlLink=url; //This URL contains new firebase storage URl for resized image.
}).catch(()=>{
this.resizedImageUrlLink=this.url; //return old url itself if any error
})
}
请注意:
const httpsReferencePath = ref(storage, storageUrl).fullPath;//This step is only required if you only have the firebase URL of actual IMAGE.If you have actual file path of stored original image,We don't have to take path and we can directly go find new file path using string manipulation.
下面是一个简单的路径扩展查找器。我没有在这里解释它,因为它不是焦点。getNewFilePath函数也可以返回类似的字符串操作
getFileNameExtension(string){
return string.split(".").pop();//get last part after last dot in the filepath
}
请参阅 firebase 文档的链接 Firebase Storage Ref Doc,其中描述了可用于引用 firebase url 的方法。