【问题标题】:How to prevent duplicate images when uploaded to firebase?上传到firebase时如何防止重复图像?
【发布时间】:2019-12-14 23:36:16
【问题描述】:

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

结构

这是我的函数“_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;

【问题讨论】:

    标签: javascript html arrays reactjs firebase


    【解决方案1】:

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

    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
              })
    

    【讨论】:

    • 我知道了,Possible Unhandled Promise Rejection (id: 0): TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
    • 对不起..我的错。忘记添加 uri 字段作为键...现在可以开始了 :)
    • 是的,这很好 :D,你能解释一下到底发生了什么以及为什么我们使用 for 循环吗? “对不起..但我想很好地理解这些!”
    • 问题是上传过程导致你有 2 个重复的数组(你好心地加入了一个有重复的数组)。这个问题很普遍,和图片上传无关。所以.. 我刚刚创建了一个终止数组重复项的通用函数。我以通用方式编写它,因此即使键字段发生更改也可以使用它(这就是它作为参数传递的原因)。是的 - 你可以标记这个答案以帮助其他遇到这个问题的人:)
    猜你喜欢
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 2012-12-09
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    相关资源
    最近更新 更多