上传到firebase时如何防止重复图像?

2024-01-26

当我想将图像上传到 firebase(实时数据库和存储)时遇到一些问题,在实时数据库中,我的图像对象默认有一张图像,并且当我上传其他图像时我不想覆盖图像所以我使用了传播运算符..., SO,
当我选择时一张图片并单击上传它们,它可以工作并保存,没有重复,但是当我选择两个或更多时,我看到至少有两个图像在上传后重复,那么我该如何解决这些问题?

结构

这是我的函数“_SaveImagesToFirebase”

class GalleryScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      images: [],
      newImages: []
    };
  }
  pickMultiple = () => {
    ImagePicker.openPicker({
      width: 300,
      height: 400,
      multiple: true,
      cropping: true
    })
      .then(img => {
        this.setState({
          newImages: img.map(i => {
            return {
              uri: i.path,
              width: i.width,
              height: i.height,
              mime: i.mime
            };
          })
        });
      })
      .then(() => this._SaveImagesToFirebase())
      .catch(e => console.log(e));
  };

    _SaveImagesToFirebase = () => {
    const uid = firebase.auth().currentUser.uid; // Provider
    const { newImages } = this.state;
    const provider = firebase.database().ref(`providers/${uid}`);
    let imagesArray = [];
    newImages.map(image => {
      let file = image.uri;
      const path = "Img_" + Math.floor(Math.random() * 1500);
      const ref = firebase
        .storage()
        .ref(`provider/${uid}/ProviderGalary/${path}`);
      ref.put(file).then(() => {
        ref
          .getDownloadURL()
          .then(images => {
            imagesArray.push({
              uri: images
            });
            console.log("Out-imgArray", imagesArray);
          })
          .then(() => {
            provider
              .update({
                Images: [...this.state.images, ...imagesArray] // Here is the issue
              })
              .then(() => console.log("done with imgs"));
          });
      });
    });
    setTimeout(() => {
      console.log("timeout", this.state.images);
    }, 8000);
  };

  componentDidMount() {
    const uid = firebase.auth().currentUser.uid;
    firebase
      .database()
      .ref(`providers/${uid}`)
      .on("value", snapshot => {
        let uri = snapshot.val().Images;
        let images = [];
        Object.values(uri).forEach(img => {
          images.push({ uri: img.uri });
        });
        this.setState({ images });
      });
  }
  render() {
    return (
      <View style={styles.container}>
        {this.state.images.length === 0 ? (
          <View
            style={{
              flex: 1,
              // alignSelf: "center",
              backgroundColor: "#fff"
            }}
          >
            <Text
              style={{
                alignSelf: "center",
                padding: 10,
                fontSize: 17,
                color: "#000"
              }}
            >
              Please upload images
            </Text>
          </View>
        ) : (
          <FlatList
            numColumns={2}
            key={Math.floor(Math.random() * 1000)}
            data={this.state.images}
            style={{
              alignSelf: "center",
              marginTop: 10
            }}
            renderItem={({ item }) => {
              return (
                // <TouchableOpacity style={{ margin: 5, flexGrow: 1 }}>
                //   <View>
                //     <Lightbox underlayColor="#fff" backgroundColor="#000">
                //       <Image
                //         key={Math.floor(Math.random() * 100)}
                //         source={{ uri: item.uri }}
                //         style={{
                //           alignSelf: "center",
                //           borderRadius: 15,
                //           width: width / 2 - 17,
                //           height: 200
                //         }}
                //         width={180}
                //         height={200}
                //         resizeMethod="scale"
                //         resizeMode="cover"
                //       />
                //     </Lightbox>
                //   </View>
                // </TouchableOpacity>
                <TouchableOpacity
                  key={Math.floor(Math.random() * 100)}
                  style={{
                    margin: 5,
                    width: width / 2 - 17,
                    height: 200
                  }}
                >
                  <Lightbox
                    style={{ flex: 1 }}
                    underlayColor="#fff"
                    backgroundColor="#000"
                  >
                    <Image
                      source={{ uri: item.uri }}
                      style={{
                        borderRadius: 15,
                        width: "100%",
                        height: "100%"
                      }}
                      resizeMethod="auto"
                      resizeMode="cover"
                    />
                  </Lightbox>
                </TouchableOpacity>
              );
            }}
            keyExtractor={(item, index) => index.toString()}
          />
        )}
        <TouchableOpacity
          onPress={() => this.pickMultiple()}
          style={{
            alignSelf: "flex-end",
            width: 57,
            height: 57,
            right: 10,
            bottom: 80,
            justifyContent: "center",
            alignItems: "center",
            borderRadius: 100,
            backgroundColor: "#fff"
          }}
        >
          <Icon name="ios-add-circle" size={70} color="#2F98AE" />
        </TouchableOpacity>
      </View>
    );
  }
}

export default GalleryScreen;

首先,创建一个合并函数,通过键操作具有重复项的数组(在您的情况下uri field)

function extractUniques(key, array) {
   const dic = {}
   for (const item of array) {
      dic[item[key]] = item
   }
   return Object.values(dic)
}

现在就用在它想要的地方

provider.update({
   Images: extractUniques('uri', [...this.state.images, ...imagesArray]) // Here is the issue
          })
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

上传到firebase时如何防止重复图像? 的相关文章

随机推荐

  • 无法在 getRequiredModulePath 的 NodeObject.getText 处读取未定义的属性“文本”

    生成浏览器应用程序包时发生错误 阶段 设置 什么可能导致此错误 来自控制台的信息 生成浏览器应用程序包 阶段 设置 类型错误 无法读取未定义的属性 文本 在 NodeObject getText opt app root src node
  • Vee-Validate validateAll() 范围

    我有一个场景 我已经划分出 范围 一个表单 以便我可以使用以下函数一次验证小块 validateScope scope return this validator validateAll scope 我想在将整个表单提交到服务器之前对其进行
  • 如何从Word 2010 Addin(用C#开发)获取“KeyPress”事件?

    如何从用 C 开发的 Word 2010 Addin 捕获 KeyPress 事件 注意 我不是在寻找 复杂 的解决方案 例如挂钩之类的东西 而是在寻找漂亮整洁的解决方案 NET 甚至来自对象模型 我 手中 的应用程序对象是 Microso
  • Angular 2在路由时传递对象

    我试图在路由时在页面之间传递对象 数组 为此我做了什么这个答案 https stackoverflow com questions 35478994 angular 2 passing object via route params pos
  • 如何为 lm() 设置平衡单向方差分析

    我有数据 dat lt data frame NS c 8 56 8 47 6 39 9 26 7 98 6 84 9 2 7 5 EXSM c 7 39 8 64 8 54 5 37 9 21 7 8 8 2 8 Less 5 c 5 9
  • getRootPane() 默认按钮 - 这是一个错误吗?

    我做了一个SSCE 请注意 它必须是 Windows 外观和感觉 import java awt import javax swing public class DefaultButtonBug private static final S
  • tbl_df 被转换为 S4 类中的列表

    当我尝试使用时tbl df在中四班 tbl df插槽似乎转变为list library tibble setOldClass c tbl df tbl data frame setClass Class TestClass slots c
  • 转置和扩展数据

    我的熊猫数据框如下所示 Country Code 1960 1961 1962 1963 1964 1965 1966 1967 1968 2015 ABW 2 615300 2 734390 2 678430 2 929920 2 963
  • FFmpeg 的 avcodec_decode_audio3 返回 -1

    我在android上使用FFmpeg来解码mp3 我在配置中设置了所有解码器启用并正确制作了 so 文件 这是为配置文件添加参数的 sh NDK android ndk r5b PLATFORM NDK platforms android
  • 如何最小化 R 包的安装大小

    在我的工作场所 我们正在为不同版本的 R 安装许多库 所需的大小正在迅速增加 我可以做什么来尽可能减少每次安装 我知道 no docs 并且我需要 with keep source EDIT 这是对我的设置的快速研究 我将我的图书馆复制到
  • 详细了解 openCV aruco 标记检测/姿态估计:亚像素精度

    我目前正在研究openCV的 aruco 模块 特别关注ArUco标记和AprilTags的poseEstimation 在研究子像素精度时 我遇到了一种奇怪的行为 如下代码所示 如果我确实提供了 完美 校准 例如 cx cy 等于图像中心
  • 在外部登录/注册 ASP.NET Web API 2.0 和 Identity 期间从 Facebook 检索其他配置文件信息

    似乎有很多关于如何使用 ASP NET Identity 和 MVC 客户端从 Facebook 配置文件获取附加信息的文档 但我似乎找不到任何关于如何从 Web API 控制器访问附加信息声明的信息 我的 Startup Auth cs
  • 为什么在 forEach 循环中不会追加列表项?

    我有一个简单的 forEach 循环 其中我尝试将列表项附加到无序列表中 但是 当我运行脚本时 我只看到添加了一个列表项 谁能解释为什么会发生这种情况 JS let bookElement document getElementsByCla
  • 如何在C#中使用文本框搜索列表视图的项目

    我有一个列表视图名称listView1 它包含计算机ID和它们的一些信息 所以我想做的是我有一个文本框名称过滤框 当我写东西时它会过滤它 它工作得很好 我的问题是它只是寻找第一列不是其他列 例如 PCNAME USER MODEL AAAA
  • 知道类中的所有变量是否为空的最佳方法是什么?

    这意味着类已初始化 但变量尚未设置 示例类 public class User String id null String name null public String getId return id public void setId
  • Groovy 不在集合中

    在 Groovy 中检查列表是否包含某些内容的惯用方法是使用in if b in a b c 但是如何很好地检查某些内容是否不在集合中呢 if g in a b c 使用逻辑看起来并不混乱 不经意的一瞥是隐藏的 在 Groovy 中是否有更
  • 如何从 ion-searchbar 获取输入?

    这是超级简单的问题 但我似乎无法弄清楚这一点 是的 我已经阅读了文档 我正在尝试获取用户输入的内容ion searchbar 在 Ionic v4 中 在他们按搜索并放入 const let 后 麻哈HTML
  • 带有 std::thread 和 std::chrono 的基本计时器

    我正在尝试使用经典方法来实现一个基本计时器 start 和 stop 我将 c 11 与 std thread 和 std chrono 一起使用 启动方法 创建一个在给定间隔时间内休眠的新线程 然后执行给定的 std function 当
  • 设置 UIView 的背景颜色会增加内存使用量

    我正在将许多 UIView 加载到 UIScrollView 上 并试图找出它们使用这么多内存的原因 经过使用 Instruments 的排除过程后 我发现设置视图的背景颜色会增加 4 倍的内存使用量 如果我不设置背景颜色 内存使用量约为
  • 上传到firebase时如何防止重复图像?

    当我想将图像上传到 firebase 实时数据库和存储 时遇到一些问题 在实时数据库中 我的图像对象默认有一张图像 并且当我上传其他图像时我不想覆盖图像所以我使用了传播运算符 SO 当我选择时一张图片并单击上传它们 它可以工作并保存 没有重