首页 > 解决方案 > 图像的本机本地文件系统存储

问题描述

作为一个学习练习,我正在编写一个基于 react-native-cli 的照片应用程序,它应该在离线模式下工作。我的意思是,应用程序提供了一种使用相机拍照或从内置图库中选择照片并将它们存储在本地文件系统中的方法,其目录路径存储在领域数据库中。以下是我的堆栈,

System: Ubuntu Linux,
react-native-cli: 2.0.1
react-native: 0.61.4,
realm@3.4.2,
react-native-image-picker@1.1.0

使用 react-native-image-picker,我可以选择一张照片或拍摄一张照片,其详细信息存储在来自 image-picker 的响应对象中,如 response.data(图像数据)和 response.uri

 ImagePicker.showImagePicker(options, (response) => {
  if (response.didCancel) {
    alert('User cancelled image picker');
  } else if (response.error) {
    alert('ImagePicker Error: ', response.error);
  } else {
    const source = { uri: response.uri };
    const sourceData = response.data;

    this.setState({
      imageSourceData: source,
    });

  }
});

In Main.js I've a simple view,
import React, { Component } from 'react';

function Item({ item }) {
  return (
    <View style={{flexDirection: 'row'}}>
      <Text>{item.picureName}</Text>
    </View>
    <Image source={uri: ....????} />   <------------- How this would work?
  )
}

export default class Main extends Component {
  state = {
    size: 0,
    pictureName: null,
    picureLocation: null,
    picureDate: new Date(),
    imageSourceData: '',
    picures: []
  }

  componentDidMount() {
    Realm.open(databaseOptions)
      .then(realm => {
      const res = realm.objects(PICTURE_SCHEMA);
      this.setState({
        pictures: res
      })
    });
  }

  render() {
    return(
      <View>
        <Image source={uri: 'data:image/jpeg;base64,' + this.state.imageSourceData}
           style:{{width: 50, height:50}}/>
        <FlatList
         data={this.state.pictures}
         renderItem={({ item }) => <Item item={item} />}
         keyExtractor={item => item.pictureID}
      >
      </View>
    )
  }
}

从 ImagePicker 获取图像后,我需要执行以下操作,

1)将此数据存储在设备上的文件中并获取文件位置。

2) 将位置与其他元数据一起存储在领域对象中

  saveButton() {
      // Store the imageSourceData into a file on a device,
      // Get the fileLocation
      // update state.picureLocation property 

      this.addOnePicture() 
  }

  addOnePicture() {
    var obj = new Object();
      obj = {
        PicureID: this.state.size + 1;
        PictureName: this.state.pictureName,
        PictureDate: this.state.pictureDate,
        PicureLocation: this.state.picureLocation
      };
    Realm.open(databaseOptions)
      .then(realm => {
        realm.write(() => {
        realm.create(PICTURE_SCHEMA, obj);
        this.setState({ size: realm.objects(PICTURE_SCHEMA).length });
      });
    })
  }

3) 可以读取领域对象列表以在“componentDidMount() 钩子”中的平面列表中显示数据

这是一段代码,但我希望它很清楚。我真的很感激任何可能的代码块的帮助/建议,

1)如何将数据(imageSourceData)存入本地文件,基本上都是填写saveButton()(我在想用react-native-fs包,这个是个好主意吗?)

2)如何在视图中显示此图像?我需要阅读在 FlatList 中呈现的内容吗?Image 语法是什么样的(检查项目组件代码)。

标签: react-nativereact-native-fs

解决方案


react-native-fs 完美运行。


推荐阅读