Firestore 上传并调整图片大小并获取压缩图片下载地址

问题描述

我安装了 Resize Images 扩展并且它正在工作。 在我的应用程序中,我有

const storageRef = firebase.storage().ref();
const imagesRef = storageRef.child(`users/${user?.id}/images`);
const imageRef = imagesRef.child(`${timestamp}.jpg`);
imageRef.put(blob).then((snapshot) => {
  snapshot.ref
    .getDownloadURL()
    .then((image_url) => {

返回的 image_url上传的原始图片,而不是调整大小的图片

如何获取调整后图片的下载地址?

我尝试将其添加到响应中:

imagesRef
  .child(`${timestamp}_1000x1000.jpg`)
  .getDownloadURL()
  .then((resized_image_url) => {
    console.log('resized_image_url',resized_image_url);
  });

当然它不能工作,因为我们不知道压缩图像什么时候准备好。 显然,在获得成功响应之前进行某种延迟循环是一种浪费。

我在想的一件事(但不喜欢作为一种解决方法)是,由于我在成功调整大小时删除了原始图像,也许我可以以某种方式收听它,并且在删除时,按照我上面的建议获取调整后的图像?

>

那我该怎么办?

解决方法

您需要通过检查是否 exists 来测试上传是否已完成,这可以在循环或从存储中获取文档引用的超时中完成。

const storageFile = bucket.file('path/to/compressed/image.jpg');
storageFile
  .exists()
  .then((exists) => {
        if (exists[0]) {
          console.log("File exists");
        } else {
          console.log("File does not exist");
        }
     })

这是 firebase 扩展的一个警告,我发现依赖专用的云函数更合适,我们可以调用它来在完成时返回一个值。