React Native文件处理 - 删除图像

时间:2016-12-27 21:02:53

标签: react-native delete-file

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

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

我检查了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);
}

remote debugging snapshot

3 个答案:

答案 0 :(得分:4)

所以我能够使用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);
      });
  }

答案 1 :(得分:1)

我还使用了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'))
    }
  }) 

答案 2 :(得分:1)

虽然已经回答了问题,但对于任何因此问题而感到沮丧的人,您也可以使用react-native fetch-blob

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