如何在reactjs中上传到Firebase存储之前调整图像大小

2024-02-02

我正在尝试调整用户上传的图像大小,以提高我的网站效率并限制我的存储使用量。

我从包中创建了一个名为 resizeFile 的函数"react-image-file-resizer"

现在我正在努力解决的是在上传到 firebase 存储之前如何调整图像大小?

这是我的代码:

const resizeFile = (file) =>
  new Promise((resolve) => {
    Resizer.imageFileResizer(file, 500, 500, "JPEG", 100, 0, (uri) => {
      resolve(uri);
    });
  });

const addProperty = async () => {
      if (
        !propName ||
     
      
      ) {
        alert("Please Enter All Required Data");
      } else {
        await firebase
          .firestore()
          .collection("Properties")
          .add({
            propname: propName,
        
          })
          .then(async (result) => {
            await Promise.all(
              selectedImages.map(async (image) => {
                const uri = await resizeFile(image);// i dont know what to do after this point
                console.log(uri);
                const storageRef = storage.ref(
                  `propertyImages/${result.id}/${image.name}`
                );
                storageRef.put(uri).then((urls) => {
                  console.log(urls);
                  storageRef.getDownloadURL().then( (downloadUrls) => {
                    console.log(downloadUrls);
                     firebase
                     .firestore()
                      .collection("Properties")
                      .doc(result.id)
                      .update({
                        propertyID: result.id,
                        imageUrls: firebase.firestore.FieldValue.arrayUnion(downloadUrls)
                      })
                      .then((res) => {
                        //handleUploadChange();
                        // alert("Property Added Successfully");
                        // window.location.reload();
                      });
                  });
                });
              })
            );
          });
      }
    };

EDIT:

好吧,我设法解决了这个问题,但仍然存在一个问题,即由于某种原因,高度永远不会调整为我指定的 maxHeight。这是为什么?

这是我修改的:

await Promise.all(
              selectedImages.map(async (image) => {
                const uri = await resizeFile(image);
                console.log(uri);
                const storageRef = storage.ref(
                  `propertyImages/${result.id}/${image.name}`
                );
                storageRef.putString(uri,'data_url').then((urls) => {
                  console.log(urls);
                  storageRef.getDownloadURL().then( (downloadUrls) => {
                    console.log(downloadUrls);
                     firebase
                     .firestore()
                      .collection("Properties")
                      .doc(result.id)
                      .update({
                        propertyID: result.id,
                        imageUrls: firebase.firestore.FieldValue.arrayUnion(downloadUrls)
                      })
                      .then((res) => {
                        //handleUploadChange();
                        // alert("Property Added Successfully");
                        // window.location.reload();
                      });
                  });
                });
              })
            );

我通过这种方式解决了 firebase 和图像大小调整问题。事实证明,该包确实会调整图像大小并将图像压缩为您指定的任何内容,但如果图像是其他格式,例如 png(因为我指定了 JPEG),它不会完全按照您的喜好调整其大小。然而,评论中有人表示这与 firebase 无关,而是通过 firebase 函数解决的。

我所要做的就是使用 .putString() ,以便返回的 base64 将转换为 firebase 存储中的字符串。因此,我的问题的答案实际上与 firebase 和 firebase 存储有很大的联系。

const resizeFile = file =>
  new Promise(resolve => {
    Resizer.imageFileResizer(file, 500, 500, "JPEG", 25, 0, uri => {
      resolve(uri);
    });
  });

const addProperty = async () => {
  if (
    !propName ||
    !price ||
    !bedroom ||
    !bathroom ||
    !area ||
    !type ||
    !category ||
    !features ||
    !services
  ) {
    alert("Please Enter All Required Data");
  } else {
    await firebase
      .firestore()
      .collection("Properties")
      .add({
        propname: propName,
        price: price,
        bedrooms: bedroom,
        bathroom: bathroom,
        exclusive: exclusive,
        area: area,
        type: type,
        category: category,
        features: features,
        services: services,
        summary: summary,
        location: location,
        salesAgentID: salesAgent,
        date: getCurrentDate(),
      })
      .then(async result => {
        await Promise.all(
          selectedImages.map(async image => {
            const uri = await resizeFile(image);
            const storageRef = storage.ref(
              `propertyImages/${result.id}/${image.name}`
            );
            storageRef.putString(uri, "data_url").then(urls => {
              storageRef.getDownloadURL().then(downloadUrls => {
                console.log(downloadUrls);
                firebase
                  .firestore()
                  .collection("Properties")
                  .doc(result.id)
                  .update({
                    propertyID: result.id,
                    imageUrls:
                      firebase.firestore.FieldValue.arrayUnion(
                        downloadUrls
                      ),
                  })
                  .then(res => {
                    setIsUploaded("Uploaded success");

                    //handleUploadChange();
                    // alert("Property Added Successfully");
                    // window.location.reload();
                  });
              });
            });
          })
        );
      });
  }
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在reactjs中上传到Firebase存储之前调整图像大小 的相关文章

随机推荐

  • OpenGL 中的矩阵堆栈已弃用?

    我刚刚读过这个 OpenGL提供了支持 用于使用标准矩阵堆栈管理坐标变换和投影 GL MODELVIEW 和 GL PROJECTION 然而 在核心 OpenGL 4 0 中 所有功能 支持矩阵堆栈已被移除 因此 我们有责任提供自己的 支
  • 克隆 git 存储库(深入)

    如何克隆存储库 使用libgit2 https github com libgit2 libgit2 我想做的正是git clone但与libgit2 我可能要问的是git clone确实很深入 这就是我到目前为止正在做的事情 初始化一个仓
  • 实体框架 - DbContextTransaction.Rollback() 中的问题

    我使用连接数据库Entity Framework 我实现了一个联系人存储库来保存联系信息 示例存储库 在上述类文件中 我声明了一个static property用于处理DBEntities i e BLabsEntities 即 Conte
  • 删除 Rails 中的关联模型

    您好 我想知道是否可以删除 Rails 中的关联 嗯 我有类似的东西 class Home lt ActiveRecord Base include settings end 在 settings rb 上我有类似的东西 module Se
  • macOS下如何查找串口的父USB设备?

    以下是我尝试枚举 Mac 上找到的所有串行端口 并遍历设备节点树以查找 USB 串行适配器的父 USB 设备的方法 import
  • 如何制作新的数组嵌套排序映射?

    我有一个数据块 如下所示 var list id 1 title thing1 week 1 day 1 id 2 title thing2 week 1 day 1 id 3 title thing3 week 1 day 2 id 4
  • 观察属性崩溃 Instruments(泄漏配置文件)Xcode 9.3 (Swift 4.1)

    当我运行以下代码 一个简化的示例 为了演示崩溃而创建 时 当我选择 运行 时 它会按预期执行 两条 os log 消息都在控制台中打印 但是 当我从内存调试导航器中的仪器中打开它时 通过按 重新启动 它崩溃了 仅在控制台中打印第一个 os
  • 如何在现有数组中追加数据而不覆盖整个数组[关闭]

    这个问题不太可能对任何未来的访客有帮助 它只与一个较小的地理区域 一个特定的时间点或一个非常狭窄的情况相关 通常不适用于全世界的互联网受众 为了帮助使这个问题更广泛地适用 访问帮助中心 help reopen questions 这是我的代
  • 在 screen_on 上更新 Android 小部件的最佳方法是什么? Android Oreo(API 26)是否支持

    我创建了一个小部件 它运行得很好 然后根据 Google Play 开发者控制台的要求 我将 targetSDK 从 23 更改为 26 切换到 Android SDK 26 后 我的应用程序小部件不再在 screen on User pr
  • “您已经拥有该商品”但 getPurchases 为空[重复]

    这个问题在这里已经有答案了 我购买了一个订阅 not a Managed Product or Unmanaged Product 昨天为了测试 我给自己退款了 然后取消了订阅 退款和取消后 当我打电话时 m billingService
  • Node.js mongodb 中的 db.getUser

    与 MongoDB shell 命令等效的命令是什么db getUser and db getUsers在 Node js MongoDB 2 x 中 我在驱动程序文档中看到db addUser and db removeUser存在但没有
  • WordPress webp 图像预览

    我已经使用以下代码更新了 wordpress 以允许 webp 上传 function webp upload mimes existing mimes existing mimes webp image webp return exist
  • 测试期间随机抛出“InvalidCastException”

    在 WatiN UI 测试中 我遇到一个问题 在运行测试时 错误有时会抛出以下错误 InvalidCastException 未由用户代码处理 无法将类型为 mshtml HTMLDocumentClass 的 COM 对象转换为接口类型
  • 在Java Servlet中读取Ajax发送的JQuery数据

    这是我的 Ajax 代码 var myJSONObject bindings ircEvent PRIVMSG method newURI regex http ajax url ships data myJSONObject succes
  • 如何在 Visual Studio 2012 中加载符号

    当我调试我的应用程序时 我看到消息 找不到或打开 PDB 文件 我似乎记得能够在调试应用程序时指定 PDB 文件的位置 我怎样才能做到这一点 我正在使用 Visual Studio 2012 添加符号位置 打开设置 工具 gt 选项 gt
  • 如何修复拥挤的 tmap 图例中的垂直空间 [R]

    如何修复 tmap 图例中的垂直空间问题 如链接的基本 R 示例中所示的问题 图例中的垂直空间 https stackoverflow com questions 38332355 vertical spaces in legend y i
  • 从下拉框中获取文本

    这将获取我的下拉菜单中选择的任何值 document getElementById newSkill value 然而 我无法找出下拉菜单当前显示的文本要查找的属性 我尝试了 文本 然后查看了W3学校 http w3schools com
  • 如何在 Python 中处理 YAML 流

    我有一个命令行应用程序 它以以下形式连续输出 YAML 数据 col0 datum0 col1 datum1 col2 datum2 col0 datum0 col1 datum1 col2 datum2 它永远这样做 我想编写一个Pyth
  • 在 Symfony 中激活 StringLoader Twig 扩展

    我正在尝试激活Twig StringLoader 扩展 http twig sensiolabs org doc functions template from string html在 Symfony 2 3 项目中 但无法获得正确的 y
  • 如何在reactjs中上传到Firebase存储之前调整图像大小

    我正在尝试调整用户上传的图像大小 以提高我的网站效率并限制我的存储使用量 我从包中创建了一个名为 resizeFile 的函数 react image file resizer 现在我正在努力解决的是在上传到 firebase 存储之前如何