React Native 文件处理 - 删除图像

React Native file handling - delete image

我正在使用 react-native-camera 来点击图片。我在状态中存储的相机数据中得到一个文件路径,如:"file:///storage/emulated/0/Pictures/IMG_20161228_021132.jpg"。我可以使用它作为使用图像组件 "Image source={{uri: this.props.note.imagePath.path}}" 显示图像的来源,并且它显示正确。

现在我想添加删除图像功能。有人可以建议如何使用上述路径在 phone 中访问此图像并将其从 phone.

中删除吗

我检查了 react-native-filesystem 但是当我使用传入此路径的 checkIfFileExists 函数时,我发现该文件不存在。不确定出了什么问题。

async checkIfFileExists(path) {

const fileExists = await FileSystem.fileExists(path);
//const directoryExists = await FileSystem.directoryExists('my-directory/my-file.txt');
console.log(`file exists: ${fileExists}`);
//console.log(`directory exists: ${directoryExists}`);
}


deleteNoteImage (note) {

console.log(note.imagePath.path);

//check if file exists
this.checkIfFileExists(note.imagePath.path);
//console.log();

note.imagePath = null;
this.updateNote(note);
}

所以我能够使用 react-native-fs

做到这一点

路径需要声明如下:

var RNFS = require('react-native-fs');

const dirPicutures = `${RNFS.ExternalStorageDirectoryPath}/Pictures`;

然后此函数删除给定图像名称的图像。

  deleteImageFile(filename) {

    const filepath = `${dirPicuturesTest}/${filename}`;

    RNFS.exists(filepath)
    .then( (result) => {
        console.log("file exists: ", result);

        if(result){
          return RNFS.unlink(filepath)
            .then(() => {
              console.log('FILE DELETED');
            })
            // `unlink` will throw an error, if the item to unlink does not exist
            .catch((err) => {
              console.log(err.message);
            });
        }

      })
      .catch((err) => {
        console.log(err.message);
      });
  }

我也用过react-native-fs。但是我没有重新创建文件路径,而是使用 react-native-camera

已经给我的文件
const file = 'file:///storage/emulated/0/Pictures/IMG_20161228_021132.jpg'
const filePath = file.split('///').pop()  // removes leading file:///

RNFS.exists(filePath)
  .then((res) => {
    if (res) {
      RNFS.unlink(filePath)
        .then(() => console.log('FILE DELETED'))
    }
  }) 

虽然已经有人回答了,但是对于遇到这个问题的任何人,您也可以使用react-native fetch-blob

RNFetchBlob.fs.unlink(path)
 .then(() => { ... })
 .catch((err) => { ... })