React Native file handling - delete image

Aman Agarwal picture Aman Agarwal · Dec 27, 2016 · Viewed 13.3k times · Source

I am using react-native-camera for clicking pictures. I get a file path like : "file:///storage/emulated/0/Pictures/IMG_20161228_021132.jpg" in the data from the Camera which I am storing in the state. I am able to use this as the source for displaying the Image using the Image component "Image source={{uri: this.props.note.imagePath.path}}" and it is displaying properly.

Now I want to add delete image functionality. Can someone suggest on how to access this image in the phone using the path mentioned above and delete it from the phone.

I checked the react-native-filesystem but when I used the checkIfFileExists function passing in this path I got that the file doesn't exist. Not sure what is going wrong.

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

Answer

Aman Agarwal picture Aman Agarwal · Jan 13, 2017

So I was able to do it using react-native-fs

The path needs to be declared as follows:

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

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

Then this function deletes the image given the image name.

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